Unit testing
Vitest is a new framework that is gaining popularity with the developers who are using Vite. Let's see how to configure it for our project.
- Install the necessary packages
pnpm add -D vitest @vitest/coverage-v8 pnpm add -D @testing-library/react jsdom @testing-library/jest-dom
- Create the
src/setupTests.ts
file and update it with the below content.
touch src/setupTests.ts
// This import will add the DOM related assertions support to the expect statement. import { beforeAll, beforeEach, afterAll, afterEach } from 'vitest' import '@testing-library/jest-dom/vitest' beforeAll(() => { // Add your global beforeAll logics }) beforeEach(() => { // Add your globalbeforeEach logics }) afterAll(() => { // Add your global afterAll logics }) afterEach(() => { // Add your global afterEach logics })
- Configure the test environment in the vite.config.ts.
- Change the import path of the
defineConfig
fromvite
tovitest/config
.
- Change the import path of the
import { defineConfig } from 'vitest/config'; export default defineConfig({ ..., test: { environment: 'jsdom', setupFiles: ['src/setupTests.ts'], coverage: { exclude: ['*.config.*', '*.d.ts'], }, }, });
- Create a test file for the app component and update it like the below,
touch src/App.test.tsx
import { render, screen } from '@testing-library/react' import { App } from './App' import { describe, expect, test } from 'vitest' describe('Component | App', () => { test('should render the app component', () => { render(<App />) expect(screen.getByText('Rendered from react app')).toBeInTheDocument() }) })
- Update the package scripts for running tests
npm pkg set scripts.test="vitest" npm pkg set scripts.test:cov="vitest run --coverage"
- Run the tests
pnpm test
- To run a particular test use the -t param.
pnpm test -- -t "add"
Sample repo
The code for this series is hosted in Github here.
Please take a look at the Github repo and let me know your feedback, and queries in the comments section.
Top comments (0)