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

时间:2019-01-16 17:24:56

标签: javascript typescript unit-testing mocking jestjs

我正在尝试验证我的方法是否正确调用了另一个导入的方法。为了我的一生,我不知道如何使用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

我尝试了各种不同的方式来设置模拟。但是我似乎无法正确理解语法。

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

1 个答案:

答案 0 :(得分:0)

最后弄清楚了答案。

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

导入需要更改为:

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

    getJsonSpy.restoreAllMocks();
  });
});
相关问题