A short walkthrough on how you can arrange React Testing Library in Vitest when utilizing Vite. The tutorial assumes that you’ve got already created a React venture with Vite both in JavaScript or TypeScript. Subsequent, set up Vitest on the command line:
npm set up vitest --save-dev
Then in your package deal.json file, add one other script which is able to run the exams ultimately:
{
...
"scripts": {
"dev": "vite",
"construct": "vite construct",
"check": "vitest",
"preview": "vite preview"
},
...
}
Create a check file someplace in your venture with the suffix check, e.g. App.check.jsx, and provides it the next content material:
import { describe, it, count on } from 'vitest';
describe('one thing truthy and falsy', () => {
it('true to be true', () => {
count on(true).toBe(true);
});
it('false to be false', () => {
count on(false).toBe(false);
});
});
You possibly can see that Vitest comes with check suites (right here:
describe
), check circumstances (right here:it
) and assertions (right here:count on().toBe()
). If in case you have been utilizing Jest earlier than, try to be accustomed to it, as a result of Vitest acts as alternative for it.You possibly can already run your exams on the command line with
npm run check
. They need to end up inexperienced.Vitest with React Testing Library
Since React Testing Library exams React parts, we have to enabled HTML in Vitest with a library like jsdom. First, set up the library on the command line:
npm set up jsdom --save-dev
Second, embrace it to the Vite configuration file:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
check: {
surroundings: 'jsdom',
},
});
Third, set up React Testing Library on the command line:
npm set up @testing-library/react @testing-library/jest-dom --save-dev
Fourth, add a check setup file in exams/setup.js and provides it the next implementation:
import { count on, afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import matchers from '@testing-library/jest-dom/matchers';
count on.lengthen(matchers);
afterEach(() => {
cleanup();
});
And final, embrace this new check setup file in Vite’s configuration file. As well as, make all imports from Vitest international, so that you just need not carry out these imports (e.g.
count on
) in every file manually anymore:import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
check: {
globals: true,
surroundings: 'jsdom',
setupFiles: './exams/setup.js',
},
});
That is it. You possibly can render React parts in Vitest now:
import { render, display screen } from '@testing-library/react';
import App from './App';
describe('App', () => {
it('renders headline', () => {
render(<App title="React" />);
display screen.debug();
});
});
Vitest is a good alternative for Jest, as a result of it’s quicker, extra fashionable, and features numerous traction nowadays.