我正在尝试验证我的方法是否正确调用另一个导入的方法。对于我的一生,我无法弄清楚如何使用 Jest 模拟导入的方法。
我想测试的方法
LandingPageManager.ts
import {getJSON} from './getJSON';
public fetchData(url: string) {
getJSON(url);
}
我想模拟的方法
getJSON.ts
export function getJSON(url: string) {
// XHR requests logic
}
测试方法
LandingPageManager.test.ts
import 'jest';
import {getJSON} from '../../../src/web/getJSON';
import {LandingPageManager} from '../../../src/web/LandingPageManager';
describe('fetchData', () => {
let manager = new LandingPageManager();
it('passes the correct URL to getJSON', () => {
const getJsonSpy = jest.mock('../../../src/web/getJSON', jest.fn());
manager.fetchData('sampleValue');
expect(getJsonSpy).toHaveBeenCalledWith('sampleValue');
getJsonSpy.restoreAllMocks();
});
});
我收到错误
jest.fn() value must be a mock function or spy
我尝试过以各种不同的方式设置模拟。但我似乎无法正确理解语法。
有人能帮我指出正确的方向吗?我觉得这应该是可能的。
最佳答案
终于找到答案了
源代码中不需要更改任何内容(导入的模块或被测试的类)。
导入需要更改为:
import {getJSON} from '../../../src/web/getJSON';
至:
import * as getJSON from '../../../src/web/getJSON';
然后我就可以直接指定用于监视的函数:
const jsonSpy = jest.spyOn(getJSON, 'getJSON');
修复测试用例
以下是它们现在如何协同工作的。
LandingPageManager.test.ts
import 'jest';
// **** 1.) Changed the below line: ****
import * as getJSON from '../../../src/web/getJSON';
import {LandingPageManager} from '../../../src/web/LandingPageManager';
describe('fetchData', () => {
let manager = new LandingPageManager();
it('passes the correct URL to getJSON', () => {
// **** 2.) Can now specify the method for direct mocking ****
const jsonSpy = jest.spyOn(getJSON, 'getJSON');
manager.fetchData('sampleValue');
expect(jsonSpy).toHaveBeenCalledWith('sampleValue');
jest.restoreAllMocks();
});
});
关于javascript - 如何使用 Jest 模拟直接导入的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54222277/