Skip to content

vitest

vitest 与 jest 类似,选择 vitest 是因为本项目使用 vite 构建,一体化的工具。

vite 配置文件中配置 vitest

ts
/// <reference types="vitest" />

export default defineConfig({
  test: {
    // ...
  },
})

运行脚本

json
{
  "scripts": {
    "test": "vitest",
    "coverage": "vitest run --coverage"
  }
}

运行测试和测试覆盖率

测试文件

目前测试文件 /app/__test__ 目录中,测试问津被识别 .(spec|test).(j/t)s(x)

工具函数

测试工具函数:

ts
import { expect, test } from 'vitest'
import { sum } from './sum'

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3)
})

sum 是 utils 的一个函数,需要对其进行测试,如果通过则

单元 React 组件

sh
pnpm jsdom @testing-library/react

@testing-library/react

ts
import React from "react";
import { describe, expect, it } from "vitest";

// react test lib
import { render, screen } from "@testing-library/react";

// component
import { App } from "../src/App";


describe("App", () => {
  it("it should be render", () => {
    render(<App />);
    expect(screen.getByText("vitest")).toBeInTheDocument();
  });
});

快照测试

ts
import { expect, it } from 'vitest'

it('toUpperCase', () => {
  const result = toUpperCase('ThisIsYourName')
  expect(result).toMatchSnapshot()
})