React Typescript Vite Testing with vitest, React Testing Library(RTL) and Mock Service Worker.
You can find me on Upwork for React tasks, work or assignment — https://www.upwork.com/freelancers/denniskiprotichk and Github — https://github.com/kimtaidennis
Jest testing library is replaced by Vitest, a next-generation testing framework driven by Vite. When React apps were produced with the create-react-app build tool, Jest and React Testing Library (RTL) were preconfigured.
With the long-standing create-react-app build tool support ending in March 2023, Vite was suggested as a replacement because to its superior performance and optimisation. Other build tools are Ban, Parcel, and so forth.
We will examine how to set up a testing environment for React projects made using Vite by utilising Vitest and the React Testing Library.
I’m going to presume that you want to develop unit tests and that you have a firm grasp of React and its guiding principles. In addition, I’m assuming you’ve already developed a React application with the Vite tool. If not, you can spin one up by using the following command into your command line and following the instructions:
npm create vite@latest
Install Vitest
Vitest must be installed as a development dependency. It is a well-liked Jest substitute for apps made with Vite.
Because its quicker, more up to date, has seen a lot of use recently, and has garnered more support from the development community, it is an excellent substitute for Jest. It is a good substitute since it is compatible with the majority of the Jest API and its ecosystem.
npm install --save-dev vitest
Once installed we need to add this command to the scripts section of our package.json file
{
"scripts": {
"test": "vitest"
}
}
Install Jsdom
Vitest simulates a portion of a web browser using the Jsdom package. We can render our components using Jsdom, allowing us to test our assertions depending on what appears on the rendered page.
Furthermore, in order to use the React Testing Library to test our React components, we also need the Jsdom library to enable HTML in Vitest. The command to install jsdom is as follows:
npm install --save-dev jsdom
After installing jsdom, we have to include jsdom in the Vite config file, which you can find at the root of your React project vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
test: {
// 👋 add the line below to add jsdom to vite
environment: 'jsdom',
}
})
Install React Testing Library (RTL)
React Testing Library is a light-weight solution for testing web pages by querying and interacting with DOM nodes. The main utilities it provides involve querying the DOM for nodes in a way that’s similar to how the user finds elements on the page.
In this way, the library helps ensure your tests give you confidence that your application will work when a real user uses it.
npm install --save-dev @testing-library/dom @testing-library/jest-dom @testing-library/react @testing-library/user-event @types/react @types/react-dom
Add a Test Setup file in the Vite configuration file
Add a setup.ts file in the root of your project or src directory and copy the follwing code:
import "@testing-library/jest-dom/vitest"
import { afterEach} from 'vitest'
import { cleanup } from '@testing-library/react'
// runs a clean after each test case (e.g. clearing jsdom)
afterEach(() => {
cleanup();
})
Lastly, include this setup test file in the vite.config.js
file and make all imports from Vitest global so that we don’t manually import(e.g. expect, describe, it) in each test file.
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: 'jsdom',
setupFiles: "./src/tests/setup.ts"
},
},
})
Render React Components in Vitest
With all the setup done, its time we write a test file. First, we create a App.test.ts file and import the App.ts(default app component) component and render the component in the test. Using the following code to render and after that you can run the Vitest test runner:
import { render, screen } from '@testing-library/react'
import App from './App'
describe('App', () => {
it('renders the App component', () => {
render(<App />)
screen.debug(); // prints out the jsx in the App component unto the command line
})
})
npm run test
From the above code, we’ve seen how Vitest combines with the React Testing Library. Both libraries complement each other.
Vitest provides us with test suites, test cases, and test runners, while React Testing Library enables us to test our components the way a user interacts with our application.
Mock Service Worker is an API mocking library that allows you to write client-agnostic mocks and reuse them across any frameworks, tools, and environments.
When testing components that have to fetch data from an API, it is advisable to create mock and stubs to simulates extact API calls but it should return the exact data structure as the real API would.
Mock Service Worker is designed to do exactly that, by intercepting the API calls within the testing environment and returning data that you can use to test with.
First, install Mock Service Worker.
npm install msw@latest --save-dev
Next, you describe the network using Request handlers (e.g. http.get()
, graphql.query()
). A request handler is responsible for intercepting a request and handling its response, which can be a mocked response, a combination of the real response and a mock, or nothing, if you only want to monitor the traffic without affecting it.
// src/mocks/handlers.js
import { http, HttpResponse } from 'msw'
export const handlers = [
// Intercept "GET https://example.com/user" requests...
http.get('https://example.com/user', () => {
// ...and respond to them using this JSON response.
return HttpResponse.json({
id: 'c7b3d8e0-5e0b-4b0f-8b3a-3b9f4b3d3b3d',
firstName: 'John',
lastName: 'Maverick',
})
}),
]
You can describe different APIs, like REST or GraphQL, including at the same time in the same handlers
array. Learn more about describing server APIs with MSW
References
I put this blog up with the help of the following resources I came across online and re-wrote it in a way I understand perfectly for my self or anyone on the web.