繁体   English   中英

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

[英]How to mock a directly-imported function using Jest?

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

    getJsonSpy.restoreAllMocks();
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM