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. Luckily, although the library’s name suggests otherwise, its makers made it compatible with Vitest.
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 '@testing-library/jest-dom/vitest';
// ...
// In vitest.config.js add (if you haven't already)
setupFiles: ['./tests/setup.js'];
And just like that, we can use jest-dom
matchers with Vitest!
// Examples
expect(getByTestId('button')).toBeDisabled();
expect(getByTestId('button')).toBeInDocument();
expect(getByTestId('invalid-form')).toBeInvalid();
expect(getByText('Visible Example')).toBeVisible();