reactjs 我有一个要测试的组件,它使用了一个钩子来导出一个函数,如何在测试前模拟导出的函数?

46qrfjad  于 2023-02-18  发布在  React
关注(0)|答案(1)|浏览(91)

我有一个叫useStartGame的钩子,它只导出一个函数,如下所示:

const useStartGame = () => {
    const startGame = (game) => { //Do something }

    return { startGame };
}

现在我有了一个使用这个钩子的组件,但是,我想在我的测试中覆盖这个函数所做的事情。我尝试在我的测试中添加以下代码:

jest.mock('@src/hooks/useStartGame', () => ({
    useStartGame: () => {
        return { startGame: jest.fn() };
    },
}));

然而,在我的测试中,我得到了这个错误:

TypeError: (0 , _useStartGame2.default) is not a function
e4yzc0pl

e4yzc0pl1#

import { render, fireEvent } from '@testing-library/react';
import { useStartGame } from '@src/hooks/useStartGame';
import MyComponent from './MyComponent';

jest.mock('@src/hooks/useStartGame', () => ({
  __esModule: true,
  useStartGame: () => ({
    startGame: jest.fn(),
  }),
}));

describe('MyComponent', () => {
  it('should call startGame on button click', () => {
    const { getByRole } = render(<MyComponent />);
    const button = getByRole('button');
    fireEvent.click(button);
    expect(useStartGame().startGame).toHaveBeenCalled();
  });
});

相关问题