我正在用 jest 编写单元测试,我必须测试一个从 3rd 方库调用构造函数的函数(测试的目标是检查调用是否使用了正确的参数
第三个 patry 库是 Popper.js
我做了一个jest.spyOn(Popper.prototype, 'constructor').mockImplementation( () => {})但它抛出来自构造函数内部的错误(因此它不是被调用的模拟函数)
这是我的测试代码
import Popper from 'popper.js';
it('should call Popper constructor with correct argument', () => {
// Arrange
jest.mockImplementation(Popper.prototype, 'constructor', () => {});
const refElem = document.createElement('div');
const popElem = document.createElement('div');
const placement = 'top';
const container = document.createElement('div');
// Act
popup.create(refElem, popElem, placement, container);
// Assert
expect(Popper.prototype.constructor).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud) 我正在尝试用 Jest 模拟一个 TypeScript 类,显然我正在做一些事情,因为收到以下错误:
error TS2743: No overload expects 1 type arguments, but overloads do exist that expect either 0 or 2 type arguments.
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
脚
export default class Foo {
bar(): number {
return Math.random()
}
}
Run Code Online (Sandbox Code Playgroud)
测试文件
import Foo from './Foo'
describe('Foo', () => {
it("should pass", () => {
const MockFoo = jest.fn<Foo>(() => ({
bar: jest.fn(() => {
return 123
}),
}))
})
})
Run Code Online (Sandbox Code Playgroud)
完整的错误:
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
src/Foo.test.ts:6:29 - error TS2743: …Run Code Online (Sandbox Code Playgroud)