Vite4.0 配置Vitest react-ts 版

717 阅读1分钟

安装 Vitest

pnpm add vitest

安装 React需要的测试库

pnpm add jsdom @testing-library/jest-dom @testing-library/react

添加 vitest.config.ts

import { defineConfig, mergeConfig } from 'vitest/config'
import viteConfig from './vite.config'

export default mergeConfig(
    viteConfig,
    defineConfig({
        test: {
            environment: "jsdom",
            setupFiles: "./vitest.setup.ts",
        },
    })
)

添加vitest.setup.ts 兼容@testing-library/jest-dom 语法

import { expect, afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
import matchers, {
  TestingLibraryMatchers,
} from "@testing-library/jest-dom/matchers";
declare global {
  namespace Vi {
    interface JestAssertion<T = any>
      extends jest.Matchers<void, T>,
        TestingLibraryMatchers<T, void> {}
  }
}
expect.extend(matchers);
afterEach(() => {
  cleanup();
});

安装@types/testing-library__jest-dom

在 tsconfig.json 添加 "types": ["@testing-library/jest-dom"] 解决在ts test文件中 @testing-library/jest-dom 语法报错问题

{
  "compilerOptions": {
    "types": ["@testing-library/jest-dom"],
    ...
  },
  ...
}

image.png

image.png