React 测试库 - 模拟函数

Ale*_*son 4 function mocking reactjs jestjs react-testing-library

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

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)
});
Run Code Online (Sandbox Code Playgroud)

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

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>
  );
}
Run Code Online (Sandbox Code Playgroud)

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

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

Emm*_*rai 5

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

这也确实有道理。单元测试应该关注结果,而不是是否调用该组件内部的特定函数。

是的,您始终可以测试该行为。例如,你可以测试一个console.log叫 cos 的东西,它是外界可见的有形的东西。

同样,如果testFuntion做了其他你可以断言的事情,你也可以测试它。

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