源码内联测试

Vitest 还提供了一种方式,可以运行与你的代码实现放在一起的测试,就像是 Rust 语言的模块测试一样

这使得测试与实现共享相同的闭包,并且能够在不导出的情况下针对私有状态进行测试。同时,它也使开发更加接近反馈循环。

指引

首先,在 if (import.meta.vitest) 内写一些测试代码并放在文件的末尾,例如:

  1. // src/index.ts
  2. // 实现
  3. export function add(...args: number[]) {
  4. return args.reduce((a, b) => a + b, 0);
  5. }
  6. // 源码内的测试套件
  7. if (import.meta.vitest) {
  8. const { it, expect } = import.meta.vitest;
  9. it('add', () => {
  10. expect(add()).toBe(0);
  11. expect(add(1)).toBe(1);
  12. expect(add(1, 2, 3)).toBe(6);
  13. });
  14. }

更新 Vitest 配置文件内的 includeSource 以获取到 src/ 下的文件

  1. // vite.config.ts
  2. import { defineConfig } from 'vitest/config';
  3. export default defineConfig({
  4. test: {
  5. includeSource: ['src/**/*.{js,ts}'],
  6. },
  7. });

然后你就可以开始测试了!

  1. $ npx vitest

生产环境构建

对于生产环境的构建,你需要设置配置文件内的 define 选项,让打包器清除无用的代码,例如,在 Vite 中

  1. // vite.config.ts
  2. import { defineConfig } from 'vitest/config'
  3. export default defineConfig({
  4. + define: {
  5. + 'import.meta.vitest': 'undefined',
  6. + },
  7. test: {
  8. includeSource: ['src/**/*.{js,ts}']
  9. },
  10. })

其他的打包器

unbuild diff // build.config.ts import { defineConfig } from 'unbuild' export default defineConfig({ + replace: { + 'import.meta.vitest': 'undefined', + }, // other options }) 了解更多: unbuild
rollup diff // rollup.config.js + import replace from '@rollup/plugin-replace' export default { plugins: [ + replace({ + 'import.meta.vitest': 'undefined', + }) ], // other options } 了解更多: rollup

TypeScript

要获得对 import.meta.vitest 的 TypeScript 的支持,添加 vitest/importMetatsconfig.json:

  1. // tsconfig.json
  2. {
  3. "compilerOptions": {
  4. "types": [
  5. + "vitest/importMeta"
  6. ]
  7. }
  8. }

完整的示例请参考 test/import-meta

说明

此功能可用于:

  • 小范围的功能或utils工具的单元测试
  • 原型设计
  • 内联断言

对于更复杂的测试,比如组件测试或E2E测试,建议使用单独的测试文件取而代之