測試註解
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,因此如果您依賴其完成,則需要等待。然而,Vitest 也會在測試結束前自動等待任何尚未完成的註解。
根據您使用的報告器,這些註解將以不同的方式呈現。
內建報告器
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 相同。您可以在使用註解的程式碼行上看到註解。目前,如果註解未在測試檔案中被使用,您將無法在 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
、warning
或 error
來配置 type
。如果類型不屬於這些選項,Vitest 將會將訊息顯示為通知。


tap
tap
和 tap-flat
報告器將註解輸出為診斷訊息,以 #
符號開頭的新行。它們會忽略所有附件,並且只輸出類型和訊息:
ok 1 - an example of a test with annotation # time=143.15ms
# notice: the message of the annotation