源内测试
Vitest 提供了一种在源代码中与实现代码一同运行测试的方式,类似于 Rust 的模块测试。
这使得测试可以与实现共享相同的作用域,从而在不导出的情况下测试私有状态。同时,这也为开发提供了更快的反馈循环。
WARNING
本指南介绍如何在源代码中编写测试。如果您需要在单独的测试文件中编写测试,请遵循 "编写测试" 指南。
配置
首先,在源文件末尾添加一个 if (import.meta.vitest) 块,并在其中编写一些测试。例如:
ts
// the implementation
export function add(...args: number[]) {
return args.reduce((a, b) => a + b, 0);
}
// in-source test suites
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest;
it('add', () => {
expect(add()).toBe(0);
expect(add(1)).toBe(1);
expect(add(1, 2, 3)).toBe(6);
});
}更新 Vitest 的 includeSource 配置,以包含 src/ 下的文件:
ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
includeSource: ['src/**/*.{js,ts}'],
},
});然后你就可以开始测试了!
bash
$ npx vitest生产环境构建
在进行生产环境构建时,你需要在配置文件中设置 define 选项,以便打包工具执行死代码消除。例如,在 Vite 中:
ts
/// <reference types="vitest/config" />
import { defineConfig } from 'vite'
export default defineConfig({
test: {
includeSource: ['src/**/*.{js,ts}'],
},
define: {
'import.meta.vitest': 'undefined',
},
})其他打包工具
unbuild
ts
import { defineBuildConfig } from 'unbuild'
export default defineBuildConfig({
replace: {
'import.meta.vitest': 'undefined',
},
// other options
})请了解更多:unbuild
Rollup
ts
import replace from '@rollup/plugin-replace'
export default {
plugins: [
replace({
'import.meta.vitest': 'undefined',
})
],
// other options
}请了解更多:Rollup
TypeScript
为了让 TypeScript 支持 import.meta.vitest,请将 vitest/importMeta 添加到你的 tsconfig.json 中:
json
{
"compilerOptions": {
"types": [
"vitest/importMeta"
]
}
}有关完整示例,请参考 examples/in-source-test。
要点
此功能适用于以下场景:
- 小型函数或工具的单元测试
- 原型开发
- 内联断言
对于组件或 E2E 测试等更复杂的测试,建议使用单独的测试文件。