简体   繁体   English

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

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

I'm trying to verify that my method is correctly invoking another, imported method. 我正在尝试验证我的方法是否正确调用了另一个导入的方法。 For the life of me, I can't figure out how to mock the imported method using Jest. 为了我的一生,我不知道如何使用Jest模拟导入的方法。

Method I want to test 我要测试的方法

LandingPageManager.ts LandingPageManager.ts

import {getJSON} from './getJSON';

public fetchData(url: string) {
    getJSON(url);
}

Method I want to mock 我要模拟的方法

getJSON.ts getJSON.ts

export function getJSON(url: string) {
    // XHR requests logic 
}

Test method 测试方法

LandingPageManager.test.ts 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();
  });
});

Error I'm getting 我收到错误

 jest.fn() value must be a mock function or spy

I've tried setting up the mock a variety of different ways. 我尝试过各种不同的方式来设置模拟。 But I can't seem to get the syntax right. 但是我似乎无法正确理解语法。

Can anyone help point me in the right direction? 谁能帮助我指出正确的方向? I feel like this should be possible. 我觉得这应该是可能的。

Finally figured out the answer. 终于找到答案了。

Nothing needed to change in the source code (either the imported module or the class under test). 无需更改源代码(导入的模块或被测类)。

The import needed to change from: 导入需要从以下更改:

import {getJSON} from '../../../src/web/getJSON';

to: 至:

import * as getJSON from '../../../src/web/getJSON';

And then I was able to directly specify the function for spying with: 然后,我可以直接指定用于监视的功能:

const jsonSpy = jest.spyOn(getJSON, 'getJSON');

Fixed test case 固定测试用例

Here's how it all works together now. 现在,这就是它们如何一起工作的方式。

LandingPageManager.test.ts 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