Would you like to buy me a ☕️ instead?
Jest is excellent, but Vitest is more excellent. Vite brought super fast bundling and hot reloading to our regular dev workflow, and Vitest is doing the same for our testing workflow. So I’m mostly transitioning away from Jest in favor of Vitest. But there are a lot of amazing tools in the Jest ecosystem, and not all of them can be easily replaced. Luckily, the Vitest API is mostly compatible with the Jest API, making it possible to reuse many tools originally built for Jest.
Extend Vitest matchers with jest-dom
The same is true for the fantastic jest-dom
library. Although we can’t install it the way the official documentation states, there is a workaround.
npm install --save-dev @testing-library/jest-dom
After installing the jest-dom
dependency, we can activate it in our Vitest setup file. If you don’t have one yet, create it.
// tests/setup.ts
import matchers from '@testing-library/jest-dom/matchers';
import { expect } from 'vitest';
expect.extend(matchers);
// ...
The trick is to import only the matchers
from jest-dom
and extend them manually with expect.extend(matchers)
. The default way does not work because jest-dom
expects the Jest expect
method to be in the global scope and tries to use it to extend its matchers. But because we use Vitest we need to extend the Vitest expect
method explicitly.
And just like that, we can use jest-dom
with Vitest.