【问题标题】:How to mock a directly-imported function using Jest?如何使用 Jest 模拟直接导入的函数?
【发布时间】:2022-02-17 02:16:37
【问题描述】:

我正在尝试验证我的方法是否正确调用了另一个导入的方法。对于我的生活,我无法弄清楚如何使用 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

我尝试了多种不同的方式来设置模拟。但我似乎无法正确使用语法。

谁能帮我指出正确的方向?我觉得这应该是可能的。

【问题讨论】:

  • 你读过例如jestjs.io/docs/en/manual-mocks?注意你应该jest.mock在测试规范之外,否则它不能被提升,你必须重新导入你正在测试的东西
  • 我做了...广泛。从文档中真的不清楚。我正在编写自定义测试模块和所有内容。我终于想出了一个答案,我会在一分钟内更新。

标签: javascript typescript unit-testing mocking jestjs


【解决方案1】:

终于找到答案了。

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

需要更改的导入:

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();
  });
});

【讨论】:

  • 示例代码中有错字。应该是:expect(jsonSpy).toHaveBeenCalledWith('sampleValue') 和 jest.restoreAllMocks()
  • 谢谢,我更新了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 2020-02-26
  • 2017-02-06
  • 2019-04-16
  • 1970-01-01
相关资源
最近更新 更多