Vitest与React测试库的详细指南

439 阅读2分钟

简要介绍了在使用Vite时如何在Vitest中设置React测试库。本教程假设你已经用Vite在JavaScript或TypeScript中创建了一个React项目。接下来,在命令行中安装Vitest

npm install vitest --save-dev

然后在你的package.json文件中,添加另一个最终将运行测试的脚本:

{  ...  "scripts": {    "dev": "vite",    "build": "vite build",    "test": "vitest",    "preview": "vite preview"  },  ...}

在项目的某个地方创建一个后缀为test的测试文件,例如App.test.jsx,并赋予它以下内容:

import { describe, it, expect } from 'vitest';
describe('something truthy and falsy', () => {  it('true to be true', () => {    expect(true).toBe(true);  });
  it('false to be false', () => {    expect(false).toBe(false);  });});

你可以看到Vitest带有测试套件(这里:describe ),测试案例(这里:it )和断言(这里:expect().toBe() )。如果你以前使用过Jest,你应该对它很熟悉,因为Vitest是作为它的替代品。

你已经可以用npm run test ,在命令行上运行你的测试。它们应该是绿色的。

Vitest与React测试库

由于React测试库测试React组件,我们需要在Vitest中用jsdom这样的库启用HTML。首先,在命令行中安装该库:

npm install jsdom --save-dev

第二,将其包含到Vite配置文件中:

import { defineConfig } from 'vite';import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/export default defineConfig({  plugins: [react()],  test: {    environment: 'jsdom',  },});

第三,在命令行上安装React测试库:

npm install @testing-library/react @testing-library/jest-dom --save-dev

第四,在test/setup.js中添加一个测试设置文件,并给它以下实现:

import { expect, afterEach } from 'vitest';import { cleanup } from '@testing-library/react';import matchers from '@testing-library/jest-dom/matchers';
// extends Vitest's expect method with methods from react-testing-libraryexpect.extend(matchers);
// runs a cleanup after each test case (e.g. clearing jsdom)afterEach(() => {  cleanup();});

最后,将这个新的测试设置文件包含在Vite的配置文件中。此外,使所有从Vitest导入的文件成为全局文件,这样你就不需要再在每个文件中手动执行这些导入(例如:expect ):

import { defineConfig } from 'vite';import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/export default defineConfig({  plugins: [react()],  test: {    globals: true,    environment: 'jsdom',    setupFiles: './tests/setup.js',  },});

就这样了。你现在可以在Vitest中渲染React组件了:

import { render, screen } from '@testing-library/react';
import App from './App';
describe('App', () => {  it('renders headline', () => {    render(<App title="React" />);
    screen.debug();
    // check if App components renders headline  });});

Vitest是Jest的一个很好的替代品,因为它更快、更现代,而且最近获得了很多的关注。