React 测试库 - 模拟一个函数

React Testing Library - mocking a function

我正在尝试测试函数是否被调用

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

如何获取被调用的模拟函数而不是 'real' 函数。

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

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

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

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

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

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