A brief walkthrough on how to set up React Testing Library in Vitest when using Vite. The tutorial assumes that you have already created a React project with Vite either in JavaScript or TypeScript. Next, install Vitest on the command line:
Then in your package.json file, add another script which will run the tests eventually:
Create a test file somewhere in your project with the suffix test , e.g. App.test.jsx , and give it the following content:
You can see that Vitest comes with test suites (here: describe ), test cases (here: it ) and assertions (here: expect().toBe() ). If you have been using Jest before, you should be familiar with it, because Vitest acts as replacement for it.
You can already run your tests on the command line with npm run test . They should turn out green.
Since React Testing Library tests React components, we need to enable HTML in Vitest with a library like jsdom . First, install the library on the command line:
Second, include it to the Vite configuration file:
Third, install React Testing Library on the command line:
Fourth, add a test setup file in tests/setup.js and give it the following implementation:
And last, include this new test setup file in Viteâs configuration file. In addition, make all imports from Vitest global, so that you donât need to perform these imports (e.g. expect ) in each file manually anymore:
Thatâs it. You can render React components in Vitest now:
Vitest is a great replacement for Jest, because it is faster, more modern, and gains lots of traction these days.