【问题标题】:React Testing Library - mocking a functionReact 测试库 - 模拟一个函数
【发布时间】:2021-11-01 18:53:42
【问题描述】:

我正在尝试测试一个函数被调用

import React from 'react';
import { render, cleanup, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import MyForm from './MyForm';

afterEach(cleanup);
const testFunction = jest.fn();
test('my form', () => {
  const { getByTestId } = render(<MyForm />);
  const myButton = getByTestId('submit-button');
  expect(myButton.tagName).toBe('BUTTON');
  fireEvent.click(myButton)
  expect(testFunction).toHaveBeenCalledTimes(1)
});

我遇到的问题是它似乎没有绑定到模拟函数,但它确实调用了组件中的函数。

import React from 'react';

export default function myForm() {
  function testFunction() {
    console.log('hello from inside');
  }
  return (
    <div>
      <form onSubmit={testFunction}>
        <input type="text" />
        <button type="submit" data-testid="submit-button">submit</button>
      </form>
    </div>
  );
}

如何获取要调用的模拟函数而不是“真实”函数。

expect(jest.fn()).toHaveBeenCalledTimes(1)
    
    Expected mock function to have been called one time, but it was called zero times.

【问题讨论】:

  • 您的testFunction 是否必须(隐藏)在 myForm 组件中?如果它是一个 prop,你可以在你的测试中传递它,然后调用 mock 函数。
  • 我已经看到这样做了——几乎在每个例子中。我会修改我的代码以适应测试。我可以,但对我来说似乎是错误的。

标签: reactjs function jestjs mocking react-testing-library


【解决方案1】:

您不能调用myForm 的内部函数。您可以测试行为和最终的有形输出,但不能测试组件的私有功能。

而且它也很有意义。单元测试应该关注结果,而不是该组件内部的特定函数是否被调用。

是的,您可以随时测试行为。例如,您可以测试 console.log 是否称为 cos,它以有形事物的形式对外界可见。

同样,如果testFuntion 做了其他您可以断言的事情,您也可以对其进行测试。

另一种选择是将testFunction 拉出并导出,以便可以在任何地方使用。然后你写一个单元测试只是testFunction的功能可能是,但不在组件单元测试的上下文中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多