Typescript 如何用Chai expect替换Jext expect的类型?
我想使用Chai作为断言库,而不是Jest库。我使用typescript,我想用Chai expect类型替换global Jest expect 我试着做一些事情,比如:Typescript 如何用Chai expect替换Jext expect的类型?,typescript,jestjs,chai,Typescript,Jestjs,Chai,我想使用Chai作为断言库,而不是Jest库。我使用typescript,我想用Chai expect类型替换global Jest expect 我试着做一些事情,比如: import chai from "chai"; type ChaiExpect = typeof chai.expect; declare global { export const expect: ChaiExpect; } global.expect = chai.expect; 但typescript抱怨
import chai from "chai";
type ChaiExpect = typeof chai.expect;
declare global {
export const expect: ChaiExpect;
}
global.expect = chai.expect;
但typescript抱怨是因为:
Cannot redeclare block-scoped variable 'expect'.ts(2451)
index.d.ts(39, 15): 'expect' was also declared here.
如何重写jest的
index.d.ts
中声明的类型?您可以重新分配global.expect在javascript端的运行时值,但在typescript端,没有简单的方法
Jest将expect
声明为全局变量(请参见@types/Jest/index.d.ts(39,15)
)。目前,typescript无法在同一块范围内重写已声明变量的类型
因此,只要保持@types/jest/index.d.ts
的原样,就无法抑制该错误
解决方案
1.捷径
使用chai的expect
最简单的方法是导入并在每个.test.ts
文件中使用它:
//sum.test.ts
从“chai”导入{expect}
从“/sum”导入{sum};
测试('1+2等于3',()=>{
期望(和(1,2))。等式(3)
});
2.艰难的道路
现在,如果您真的无法忍受从“chai”
行重复导入{expect}
node\u modules/@types/jest
移动到types/jest
,确保它已进入node\u modules
文件夹。同时从“package.json=>devdependences”中删除“@types/jest”types/jest/index.d.ts
,将expect
的类型替换为chai的类型。您需要将此自定义类型声明提交给git repojestSetup.js
并添加以下一行:jest.config.js
中,设置:expect
// index.d.ts
+ /// <reference types="chai" />
- declare const expect: Expect
+ declare const expect: Chai.ExpectStatic
{
"compilerOptions": {
"typeRoots": ["node_modules/@types", "types"],
...
}
global.expect = require("chai").expect
setupFilesAfterEnv: ['./jestSetup.js'],
// or `setupTestFrameworkScriptFile` for older version.