Testing - Vitest
安装
- npm
- Yarn
- pnpm
npm install -D vitest @vitest/ui
yarn add --dev vitest @vitest/ui
pnpm add -D vitest @vitest/ui
- npm
- Yarn
- pnpm
npm install -D @testing-library/jest-dom @testing-library/react @testing-library/user-event jsdom
yarn add --dev @testing-library/jest-dom @testing-library/react @testing-library/user-event jsdom
pnpm add -D @testing-library/jest-dom @testing-library/react @testing-library/user-event jsdom
npm pkg set scripts.test="vitest --ui"
配置
vitest.config.ts
import { defineConfig, mergeConfig } from 'vitest/config';
import viteConfig from './vite.config.ts';
const vitestConfig = defineConfig({
test: {
environment: 'jsdom',
globals: true,
setupFiles: './vitest.setup.ts',
css: true,
},
});
export default mergeConfig(viteConfig, vitestConfig);
vitest.setup.ts
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(() => {
cleanup();
});
Test
测试项目由 npm create vite@latest my-app-react -- --template react-ts
生成
src/App.test.tsx
import { expect, it, describe } from 'vitest';
import { render, screen } from '@testing-library/react';
import App from './App';
describe('Input', async () => {
it('app', () => {
render(<App />);
const element = screen.getByRole('heading', { level: 1 });
expect(element).toBeInTheDocument();
});
});
常见问题
- Error: Uncaught [TypeError: Cannot destructure property 'basename' of 'React__namespace.useContext(...)' as it is null.]
如果项目中使用了 React Router
,同时测试组件中包含 Link
等组件,需要将组件包裹在 MemoryRouter
等组件中进行测试,V5 版本官方文档说明