如何使用 Jest 模拟直接导入的函数?

Cug*_*uga 2 javascript unit-testing mocking typescript jestjs

我正在尝试验证我的方法是否正确调用了另一个导入的方法。对于我的一生,我不知道如何使用 Jest 来模拟导入的方法。

我想测试的方法

登陆页面管理器.ts

import {getJSON} from './getJSON';

public fetchData(url: string) {
    getJSON(url);
}
Run Code Online (Sandbox Code Playgroud)

我想模拟的方法

获取JSON.ts

export function getJSON(url: string) {
    // XHR requests logic 
}
Run Code Online (Sandbox Code Playgroud)

测试方法

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

我得到的错误

 jest.fn() value must be a mock function or spy
Run Code Online (Sandbox Code Playgroud)

我试过以各种不同的方式设置模拟。但我似乎无法正确使用语法。

任何人都可以帮助我指出正确的方向吗?我觉得这应该是可能的。

Cug*_*uga 9

终于想出了答案。

无需更改源代码(导入的模块或被测类)。

导入需要更改为:

import {getJSON} from '../../../src/web/getJSON';
Run Code Online (Sandbox Code Playgroud)

到:

import * as getJSON from '../../../src/web/getJSON';
Run Code Online (Sandbox Code Playgroud)

然后我能够直接指定用于监视的函数:

const jsonSpy = jest.spyOn(getJSON, 'getJSON');
Run Code Online (Sandbox Code Playgroud)

固定测试用例

这是现在如何协同工作。

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(getJsonSpy).toHaveBeenCalledWith('sampleValue');

    getJsonSpy.restoreAllMocks();
  });
});
Run Code Online (Sandbox Code Playgroud)