我想使用Chai作为Assert库,而不是Jest。我使用typescript,并且我想用Chai expect类型替换全局Jest expect。
我试着这样做:
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
内部声明的类型?
1条答案
按热度按时间ttcibm8c1#
You can re-assign
global.expect
's runtime value on javascript side, on the typescript side however, no easy way out.Jest declares
expect
as a global variable (see@types/jest/index.d.ts(39, 15)
). Currently typescript provides no way to override a readily declared variable's type in the same block-scope.So as long as you keep
@types/jest/index.d.ts
the way it is, nothing you can do to suppress that error.Solution
1. The easy way
The easiest way to use chai's
expect
, is simply import and use it in every.test.ts
file:2. The hard way
Now if you really can't live with that repeating
import { expect } from 'chai'
line, here's the harder path:node_modules/@types/jest
totypes/jest
, make sure it's gone in thenode_modules
folder. Also delete "@types/jest" from "package.json => devDependencies".types/jest/index.d.ts
, replace the type ofexpect
with chai's. You need to commit this customized type declaration to your git repo.tsconfig.json
, add:jestSetup.js
and add this one-liner:jest.config.js
, set:There you go. You can now use chai
expect
right in the global scope.