類型 - 我如何在 TypeScript 中全域匯入 Chai 的 'expect()' 函數?
其他相關問題只是關於 JavaScript 提問,但我知道 Chai 團隊已經提供了 'chai/register-expect' 等。
我正在從 Jest 遷移到 Chai,當我使用 Jest 時,只需在 tsconfig.json 文件的 "types" 欄位中輸入 'jest' 就可以了。然後 expect 函數會自動通過 @types/jest index.d.ts 進行引用。
但是 @types/chai 或 Chai 並不支持這個。他們建議,在報告問題之前,先在 Stack Overflow 上發帖。到底是怎麼回事,對吧?
在查了這個之後,我發現每個人都在每個檔案中引入 'expect' 函數,像 TypeORM 或其他 TypeScript 專案一樣……天啊,這實在是太糟糕了。
我為什麼每個檔案都要匯入 expect()?難道沒有辦法避免這樣做嗎?
我可以回到 Jest,但那個效能糟糕得像糞便一樣。對所有檔案來說,直接匯入 expects 會比較好。
mocha -r chai/register-expect 也不起作用。
我在測試:
npx mocha -r node_modules/ts-node/register/transpile-only -r chai/register-expect -r ts-node/register -r tsconfig-paths/register some.test.ts
這是我的 tsconfig.json 文件。
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es5",
"noImplicitAny": false,
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": "src",
"skipLibCheck": true,
"downlevelIteration" : true,
"paths": {
... bla bla
"main/*" : [
"main/*"
],
"controllers/*" : [
"main/controllers/*"
],
"middleware/*" : [
"main/middleware/*"
],
"*": [
"node_modules/*"
]
},
"types" : [
"node",
"mocha",
"chai"
],
"typeRoots": [
"node_modules/@types",
"types"
],
"lib": [
"es2017",
"dom"
],
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule" : true
},
"exclude": [
"node_modules"
],
"include": [
"src/**/*.ts",
"**/*.test.ts"
]
}
答案#1
chai/register-expect 將會註冊一個全域的 Chai 函數 expect。
你需要通過建立自訂的定義檔來向你的 TypeScript 編譯器解釋你擁有它。
建立目錄結構:
typings
global
index.d.ts
在你的 index.d.ts 文件中,添加以下內容:
declare const expect: Chai.ExpectStatic
現在你的 tsconfig.json 應該像這樣:
"typeRoots": [
"node_modules/@types", "./typings"
],
"types": [
"mocha",
"chai",
"node",
"global"
]
注意 typings 目錄以及 global 模組的導入。
這是必要的,因為 ts-node 通常不會在意你的自訂型別定義。
