我想使用柴作为断言库,而不是Jest库。我使用类型记录,我想用柴期期待的类型来代替全球Jest expect。
我试着做这样的事情:
import chai from "chai";
type ChaiExpect = typeof chai.expect;
declare global {
export const expect: ChaiExpect;
}
global.expect = chai.expect;但是打字本抱怨是因为:
Cannot redeclare block-scoped variable 'expect'.ts(2451)
index.d.ts(39, 15): 'expect' was also declared here.如何覆盖jest的index.d.ts中声明的类型?
发布于 2019-04-13 09:32:59
您可以在javascript端,在类型记录端重新分配global.expect的运行时值,但这不是一条容易的出路。
Jest将expect声明为全局变量(参见@types/jest/index.d.ts(39, 15))。目前,类型记录无法覆盖同一块范围内容易声明的变量的类型。
因此,只要保持@types/jest/index.d.ts的原样,就无法阻止该错误。
解决方案
1.简单的方法
使用chai的expect最简单的方法是在每个.test.ts文件中导入并使用它:
// sum.test.ts
import { expect } from 'chai'
import { sum } from './sum';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).eq(3)
});2.艰难的道路
现在,如果您真的不能忍受重复的import { expect } from 'chai'行,那么下面是更难的路径:
node_modules/@types/jest移动到types/jest,确保它在node_modules文件夹中消失。还删除"package.json => devDependencies“中的”@type/jest“。types/jest/index.d.ts,用chai替换expect类型。您需要将这个定制的类型声明提交给您的git。// index.d.ts
+ /// <reference types="chai" />
- declare const expect: Expect
+ declare const expect: Chai.ExpectStatictsconfig.json中添加:{
"compilerOptions": {
"typeRoots": ["node_modules/@types", "types"],
...
}jestSetup.js并添加以下一行:global.expect = require("chai").expectjest.config.js中,set:setupFilesAfterEnv: ['./jestSetup.js'],
// or `setupTestFrameworkScriptFile` for older version.这就对了。现在可以在全局范围内直接使用chai expect。
https://stackoverflow.com/questions/55661846
复制相似问题