测试过滤
过滤、超时以及套件和测试的并发
命令行界面
你可以使用命令行(CLI)按名称过滤测试文件:
bash
$ vitest basic
这将只执行名称中包含 basic
的测试文件,例如:
basic.test.ts
basic-foo.test.ts
basic/foo.test.ts
你还可以使用 -t, --testNamePattern <pattern>
选项按完整的测试名称进行过滤。这在你希望按文件中定义的测试名称而非文件名进行过滤时很有帮助。
从 Vitest 3 开始,你还可以通过文件名和行号指定要运行的测试:
bash
$ vitest basic/foo.test.ts:10
WARNING
请注意,Vitest 要求使用完整的文件路径才能使此功能正常运行。文件路径可以是相对于当前工作目录的路径,也可以是绝对文件路径。
bash
$ vitest basic/foo.js:10 # ✅
$ vitest ./basic/foo.js:10 # ✅
$ vitest /users/project/basic/foo.js:10 # ✅
$ vitest foo:10 # ❌
$ vitest ./basic/foo:10 # ❌
目前,Vitest 也不支持行号范围:
bash
$ vitest basic/foo.test.ts:10, basic/foo.test.ts:25 # ✅
$ vitest basic/foo.test.ts:10-25 # ❌
指定超时
你可以选择将超时时间(毫秒)作为测试的第三个参数。默认值为 5 秒。
ts
import { test } from 'vitest';
test('name', async () => {
/* ... */
}, 1000);
钩子(Hooks)也可以接收超时时间,默认值同样为 5 秒。
ts
import { beforeAll } from 'vitest';
beforeAll(async () => {
/* ... */
}, 1000);
跳过套件和测试
使用 .skip
跳过某些套件或测试:
ts
import { assert, describe, it } from 'vitest';
describe.skip('skipped suite', () => {
it('test', () => {
// 套件已跳过,此断言不会执行
assert.equal(Math.sqrt(4), 3);
});
});
describe('suite', () => {
it.skip('skipped test', () => {
// 测试已跳过,此断言不会执行
assert.equal(Math.sqrt(4), 3);
});
});
选择要运行的套件和测试
使用 .only
仅运行某些套件或测试:
ts
import { assert, describe, it } from 'vitest';
// 仅运行此套件(以及其他标记为 .only 的套件)
describe.only('suite', () => {
it('test', () => {
assert.equal(Math.sqrt(4), 3);
});
});
describe('another suite', () => {
it('skipped test', () => {
// 此测试将被跳过,因为当前处于 .only 模式
assert.equal(Math.sqrt(4), 3);
});
it.only('test', () => {
// 仅运行此测试(以及其他标记为 .only 的测试)
assert.equal(Math.sqrt(4), 2);
});
});
未实现的套件和测试
使用 .todo
为待实现的套件和测试创建占位符:
ts
import { describe, it } from 'vitest';
// 报告中将显示此套件的记录,标记为待办
describe.todo('unimplemented suite');
// 报告中将显示此测试的记录,标记为待办
describe('suite', () => {
it.todo('unimplemented test');
});