我有两个类
ClassA
和 ClassB
只包含静态方法。 ClassA
中的一个方法,称为staticMethodA()
,调用来自ClassB
的静态方法,称为staticMethodB
。
import { ClassB } from './classB'
export class ClassA {
public static async staticMethodA() {
return await ClassB.staticMethodB();
}
}
在为
staticMethodA()
进行单元测试时,我想模拟staticMethodB()
以更好地隔离staticMethodA()
。按照现有的在线指导,我创建了以下测试:
describe('staticMethodA', () => {
let classA;
const mockStaticMethodB = jest.fn().mockResolvedValue({}); //return dummy object
beforeAll(() => {
// Mocking ClassB
jest.mock('../src/classB', () => () => ({
ClassB: {
staticMethodB: mockStaticMethodB
}
})}};
// Importing ClassA after mocking ClassB so it references the mock
classA = require('../src/classA');
}
it('should call mockStaticMethodB', async () => {
//The object returned from require is an object containing ClassA
const actual = await classA.ClassA.staticMethodA();
expect(actual).toBe({}); // dummyObject
}
afterAll(() => {
jest.unmock('../src/classB');
});
}
当 staticMethodA 调用 staticMethodB 时,我得到一个错误,指出 ClassB 未定义。当我在
return await ClassB.staticMethodB();
上设置断点时,我看到有一个名为 classB_1
的变量可用但不是 ClassB
.
我已经尝试了以下资源中的一些模拟构建策略,但仍然导致
ClassB
未定义:
在这种情况下,有几件事需要改变。我已经在本地测试过它并且有效。
// classa.test.ts
import {ClassA} from '../classA';
// we are importing ClassB directly
// this will be the mocked version
import {ClassB} from '../classB';
// mock should be hoisted to the top of the module
jest.mock('../classB', () => {
return {
ClassB: {
staticMethodB: jest.fn(),
},
};
});
describe('classA', () => {
it('should call mockStaticMethodB', async () => {
// since ClassB is a mock we can provide the return value for this test case only
(ClassB.staticMethodB as jest.Mock).mockReturnValueOnce(42);
const actual = await ClassA.staticMethodA();
// note that in both mock and here we are using 42 for comparison as it works with `expect().toBe()`
// if we wanted to compare objects we would use `expect().toEqual()` instead
expect(actual).toBe(42);
});
});