如何测试在 react-testing-library 中调用了函数 prop

How to test that a function prop was called in react-testing-library

有 3 个文件:

文件 1:helpers.js

export const helpers = () => ({
  bar: () => 'Bar was called',
});

文件 2:TestComponent.js

import React from 'react';
import { helpers } from './helpers';

const TestComponent = () => {
  const { bar } = helpers();
  return (
    <><button onClick={bar}/></>
  );
};

export default TestComponent;

文件 3:TestComponent.test.js

import React from 'react';
import userEvent from '@testing-library/user-event';
import { screen, render } from '@testing-library/react';
import TestComponent from './TestComponent';
import { helpers } from './helpers';

jest.mock('./helpers', () => ({
  helpers: jest.fn(),
}));

test('bar is called', () => {
  helpers.mockImplementation(() => ({
    bar: jest.fn(),
  }));

  render(
    <TestComponent />,
  );

  userEvent.click(screen.getByRole('button'));

  expect(???????).toHaveBeenCalled();
});

这一行是关键:

expect(???????).toHaveBeenCalled();

问题:如何测试bar函数是否被调用?我期待类似于 expect(helpers().bar) 的东西会起作用。但事实并非如此。

将函数保存在变量中并在 expect

中使用它
test('bar is called', () => {
  const bar = jest.fn()
  helpers.mockImplementation(() => ({bar}));

  render(
    <TestComponent />,
  );

  userEvent.click(screen.getByRole('button'));

  expect(bar).toHaveBeenCalled();
});