【问题标题】:How to mock a method which is part of a node-module using jest?如何使用 jest 模拟作为节点模块一部分的方法?
【发布时间】:2022-01-07 14:38:54
【问题描述】:

单击按钮时,我需要模拟一个函数。该函数位于不同的文件中。这个函数使用来自 node_modules 的方法

import { recordCounter } from '../instrumentation/instrumentation';
<Button
  onClick={() => {
    recordCounter(`createTicketClicked`);
  }}
  text="Create Ticket"
/>

在instrumentation.ts中

import { newFederatedInstrumentation } from 'metrics';

const instance = newFederatedInstrumentation('myMetrics');
export const recordCounter = instance.recordCounter;

在测试中,我需要模拟方法recordCounter,看看它是否被调用以及使用什么值?

【问题讨论】:

  • 你可以使用jest.fn()toBeCalledWith
  • 类似的东西? const recordCounter = jest.fn(); expect(recordCounter).toHaveBeenCalledWith("createTicketClicked"); 抛出错误。
  • 是的,就像那样。你看到了什么错误?
  • 我收到一个错误。 Expected: "createTicketClicked" Number of calls: 0
  • 如何在测试中“点击”按钮?看看测试代码会很有帮助。

标签: reactjs jestjs


【解决方案1】:

在您的情况下,您有两个选项可以模拟此方法。第一个选项是添加一个道具,您可以在其中提供模拟方法并对此有一些期望:

it('should call a method upon click', () => {
    const mockedMethod = jest.fn();     
    const { getByTestId } = render(<Component method={mockedMethod} />);    

    const button = getByTestId("button");     
    button.click();    

    expect(mockedMethod).toHaveBeenCalledWith("some-value");     
});

第二种选择是在模块级别模拟该方法,并对此有几乎相同的期望。

import { method } from "./method"

jest.mock("./method")

it('should call a method upon click', () => {  
    const { getByTestId } = render(<Component />);    

    const button = getByTestId("button");     
    button.click();    

    expect(method).toHaveBeenCalledWith("some-value");     
});

这两个选项都有其有效用途。

【讨论】:

    猜你喜欢
    • 2019-08-21
    • 2018-07-14
    • 2019-08-15
    • 1970-01-01
    • 2018-06-21
    • 2019-12-09
    • 2018-02-19
    • 2019-12-02
    相关资源
    最近更新 更多