进阶 vitest.dev 2026-10-22 19:00:41 · 19 阅读

第8章 Vitest 测试注解功能详解

测试注解 ​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 })

await annotate('creates a file with text', { contentType: 'text/markdown', body: 'Hello markdown', bodyEncoding: 'utf-8', }) }) ```

警告:annotate 函数返回 Promise,如果依赖其结果,需要 await。不过,如果测试结束前存在未 await 的注解,Vitest 也会自动等待它们完成。

不同报告器的展示方式各异。

内置报告器

​默认 默认报告器仅在测试失败时打印注解:

``` ⎯⎯⎯⎯⎯⎯⎯ 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 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 一致。你可以在调用注解的那一行看到它。目前,如果注解未在测试文件中调用,你将无法在 UI 中看到它。我们计划支持独立的测试摘要视图,届时将可见。

​junit junit 报告器将注解列在 testcase 的 properties 标签内。JUnit 报告会忽略所有附件,仅打印类型和消息。

```xml ```

​github-actions github-actions 报告器默认将注解作为 notice 消息打印。你可以通过传入第二个参数来配置类型,可选值为 notice、warning 或 error。如果类型不属于这些值,Vitest 将默认以 notice 形式显示消息。

​tap tap 和 tap-flat 报告器将注解作为诊断消息打印在新行,行首以 # 符号开始。它们会忽略所有附件,仅打印类型和消息:

``` ok 1 - an example of a test with annotation # time=143.15ms # notice: the message of the annotation ```

评论 (0)