如何将Jest expect类型替换为Chai expect?

gmxoilav  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(200)

我想使用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内部声明的类型?

ttcibm8c

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:

// 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. The hard way

Now if you really can't live with that repeating import { expect } from 'chai' line, here's the harder path:

  1. Move node_modules/@types/jest to types/jest , make sure it's gone in the node_modules folder. Also delete "@types/jest" from "package.json => devDependencies".
  2. Modify types/jest/index.d.ts , replace the type of expect with chai's. You need to commit this customized type declaration to your git repo.
// index.d.ts

+ /// <reference types="chai" />

- declare const expect: Expect
+ declare const expect: Chai.ExpectStatic
  1. In your tsconfig.json , add:
{
  "compilerOptions": {
    "typeRoots": ["node_modules/@types", "types"],
    ...
}
  1. Create jestSetup.js and add this one-liner:
global.expect = require("chai").expect
  1. in jest.config.js , set:
setupFilesAfterEnv: ['./jestSetup.js'],
// or `setupTestFrameworkScriptFile` for older version.

There you go. You can now use chai expect right in the global scope.

相关问题