我在使用 Jest 模拟函数时遇到错误

I am Getting an Error Whilst Mocking a Function Using Jest

我正在编写我的第一个模拟函数。我在模拟功能上遇到错误,如果我控制我正在获得 action={[Function]} 的项目。 谁能帮我模拟这个功能?

错误:

Expected: [Function mockConstructor]
Received: [Function anonymous]

我的代码:

export const transform = React.memo<transform Props>((props) => (
<Container
 actions={[
  transformitemLeft(
    'Clean',
    () => {
      props.onschedule()
    },
  ),
 />

测试用例:

const onscheduleMock = jest.fn()
test('Actions', () => {
const item = render().find(transform)
expect(item.at(0).prop('action')).toBe(onscheduleMock )
})

为了回答您的评论,这里有一种使用函数式 React 组件验证 .toHaveBeenCalled() 模拟函数调用的方法:

// Component

const MyButton = ({ handleSubmit }) => {
  return (
    <button
      id="step-section-save-button"
      className="button-save"
      data-testid="save-button"
      onClick={() => handleSubmit()}
    >
      Save
    </button>
  );
}

export default MyButton;
// test file
import React from 'react';
import { render, getByText, fireEvent, getByTestId } from '@testing-library/react';

it('should trigger the handleSubmit function', () => {
  const mockHandleSubmit = jest.fn();
  const { container } = render(
    <MyButton handleSubmit={() => mockHandleSubmit()} />  // mockedFunction is passed as props
  );

  const buttonComponent = getByTestId(container, "save-button");
  fireEvent.click(buttonComponent); // Fire the event that will trigger my mocked function

  expect(mockHandleSubmit).toHaveBeenCalled();
});