[英]Mocha testing TypeScript with types defined in global scope
我目前正在為一個遺留應用程序構建一個測試框架,該應用程序有許多types.ts
文件,這些文件定義了在文件頂層沒有任何導入/導出的類型。 例如,我們有一個Pills/types.ts
文件,其中僅包含
interface Pills {
id: number,
// more properties
}
根據 TypeScript 文檔,如果沒有導入/導出,該文件被視為一個模塊,並且是全局 scope 的一部分。 任何使用Pills
類型的文件都使用它而不顯式導入該類型。 這目前在我們的 web 應用程序中運行良好,該應用程序作為webpack
包運行。
但是,當我嘗試使用在 NodeJS 上運行的mocha
運行測試時,出現以下錯誤:
app/javascript/components/HardwareTestReports/table.tsx(18,16): error TS2304: Cannot find name 'Pill'.
app/javascript/components/HardwareTestReports/table.tsx(106,56): error TS2304: Cannot find name 'Pill'.
這是因為mocha
在 NodeJS 上運行,需要文件顯式聲明導出/導入?
我的.tsconfig
看起來像這樣:
{
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es7", "dom", "esnext"],
"module": "es6",
"moduleResolution": "node",
"sourceMap": true,
"target": "es6",
"jsx": "react",
"esModuleInterop": true
},
"exclude": ["node_modules", "vendor", "public", "test"],
"compileOnSave": false
}
我的 package.json 有以下測試腳本:
"scripts": {
"test": "TS_NODE_PROJECT='./tsconfig.json' mocha -r ts-node/register -r esm test/**/*.ts"
},
這是因為mocha
在 NodeJS 上運行,需要文件顯式聲明導出/導入?
重構types.ts
文件以顯式導入/導出它們的類型目前不是一個選項 - 我們有許多相互交織的類型,並且更新每個文件以包含導入/導出將涉及觸及代碼庫中的幾乎每個文件 - 絕對是一個長期項目處理。
假設您的tsconfig
僅用於測試,您可以告訴 ts-node 包含自定義類型:
在tsconfig.json
{
"ts-node": {
"files": true
},
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es7", "dom", "esnext"],
"module": "es6",
"moduleResolution": "node",
"sourceMap": true,
"target": "es6",
"jsx": "react",
"esModuleInterop": true
},
"exclude": ["node_modules", "vendor", "public", "test"],
"compileOnSave": false,
"files": ["Pills/types.ts"] // WHere you keep the types
"include": ["test/**/*.ts"] // Wherever you keep your tests
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.