测试注解
Vitest 支持通过 context.annotate
API 为测试添加自定义消息和文件注解。这些注解将附加到测试用例,并通过 onTestAnnotate
钩子传递给报告器。
ts
test('hello world', async ({ annotate }) => {
await annotate('this is my test');
if (condition) {
await annotate("this should've errored", 'error');
}
const file = createTestSpecificFile();
await annotate('creates a file', { body: file });
});
WARNING
annotate
函数返回 Promise,因此如果你需要等待其完成,需要使用 await
。然而,Vitest 也会在测试结束前自动 await
任何未显式 await
的注解。
根据你使用的报告器,这些注解的显示方式可能会有所不同。
内置报告器
default
default
报告器仅在测试失败时显示注解:
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
FAIL example.test.js > an example of a test with annotation
Error: thrown error
❯ example.test.js:11:21
9 | await annotate('annotation 1')
10| await annotate('annotation 2', 'warning')
11| throw new Error('thrown error')
| ^
12| })
❯ example.test.js:9:15 notice
↳ annotation 1
❯ example.test.js:10:15 warning
↳ annotation 2
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
verbose
在 TTY 终端中,verbose
报告器的行为与 default
报告器相似。然而,在非 TTY 环境中,verbose
报告器也会在每次测试后显示注解。
✓ example.test.js > an example of a test with annotation
❯ example.test.js:9:15 notice
↳ annotation 1
❯ example.test.js:10:15 warning
↳ annotation 2
html
HTML 报告器显示注解的方式与用户界面(UI)相同。你可以在调用注解的行中看到它。目前,如果注解未在测试文件中调用,则无法在用户界面中看到。我们计划支持单独的测试摘要视图,届时注解将可见。


junit
junit
报告器将注解列在测试用例的 properties
标签内。JUnit 报告器将忽略所有附件,并且仅打印类型和消息。
xml
<testcase classname="basic/example.test.js" name="an example of a test with annotation" time="0.14315">
<properties>
<property name="notice" value="the message of the annotation">
</property>
</properties>
</testcase>
github-actions
github-actions
报告器默认会将注解显示为 notice message。你可以通过将第二个参数设置为 notice
、warning
或 error
来配置 type
。如果类型不属于这些,Vitest 将把消息显示为 notice。


tap
tap
和 tap-flat
报告器将注解显示为诊断消息,并在新行上以 #
符号开头。它们将忽略所有附件,并且仅打印类型和消息:
ok 1 - an example of a test with annotation # time=143.15ms
# notice: the message of the annotation