型別測試
Vitest 允許你使用 expectTypeOf
或 assertType
語法來撰寫型別測試。預設情況下,所有在 *.test-d.ts
檔案中的測試都會被視為型別測試,但你可以使用 typecheck.include
設定選項來更改此行為。
在底層,Vitest 會調用 tsc
或 vue-tsc
,具體取決於你的配置,並解析其結果。如果 Vitest 發現你的原始碼中有任何型別錯誤,它也會將其列印出來。你可以使用 typecheck.ignoreSourceErrors
設定選項來停用此功能。
請記住,Vitest 不會執行或編譯這些檔案,它們僅由編譯器進行靜態解析,因此,你不能使用任何動態陳述式。這意味著,你不能使用動態測試名稱,以及 test.each
、test.runIf
、test.skipIf
、test.concurrent
等 API。但是你可以使用其他 API,例如 test
、describe
、.only
、.skip
和 .todo
。
型別檢查也支援使用 CLI 標誌,例如 --allowOnly
和 -t
。
import { assertType, expectTypeOf } from 'vitest';
import { mount } from './mount.js';
test('my types work properly', () => {
expectTypeOf(mount).toBeFunction();
expectTypeOf(mount).parameter(0).toMatchTypeOf<{ name: string }>();
// @ts-expect-error name is a string
assertType(mount({ name: 42 }));
});
在測試檔案中觸發的任何型別錯誤都將被視為測試錯誤,因此你可以使用任何你想要的類型技巧來測試專案的型別。
你可以在 API 章節 中看到可用的匹配器。
讀取錯誤訊息
如果你正在使用 expectTypeOf
API,你可能會注意到難以閱讀的錯誤或意外的錯誤。
expectTypeOf(1).toEqualTypeOf<string>();
// ^^^^^^^^^^^^^^^^^^^^^^
// index-c3943160.d.ts(90, 20): Arguments for the rest parameter 'MISMATCH' were not provided.
這是因為 expect-type
處理類型錯誤的方式所致。
不幸的是,TypeScript 不提供未經修補的類型元數據,因此我們目前無法提供有用的錯誤訊息,但是 TypeScript 專案正在進行相關工作 來解決這個問題。如果你想要更好的訊息,請向 TypeScript 團隊表達對該 PR 的關注。
如果你發現使用 expectTypeOf
API 並找出錯誤很困難,你可以隨時使用更簡單的 assertType
API:
const answer = 42;
assertType<number>(answer);
// @ts-expect-error answer is not a string
assertType<string>(answer);
TIP
當使用 @ts-expect-error
語法時,你可能需要確保你沒有拼寫錯誤。你可以通過在 test.include
設定選項中包含你的型別檔案來做到這一點,這樣 Vitest 實際上也會 執行 這些測試,並在發生 ReferenceError
時失敗。
這將通過,因為它期望一個錯誤,但是單詞 “answer” 有一個拼寫錯誤,所以這是一個誤報:
// @ts-expect-error answer is not a string
assertType<string>(answr); //
執行型別檢查
將此命令添加到 package.json
的 scripts
部分:
{
"scripts": {
"typecheck": "vitest typecheck"
}
}
現在你可以執行型別檢查:
# npm
npm run typecheck
# yarn
yarn typecheck
# pnpm
pnpm run typecheck
Vitest 使用 tsc --noEmit
或 vue-tsc --noEmit
,具體取決於你的配置,因此你可以從你的流程中移除這些指令碼。