【问题标题】:How can I mock an imported React hook/module and test that it's being called properly on different test cases using Jest如何模拟导入的 React 钩子/模块并使用 Jest 在不同的测试用例中测试它是否被正确调用
【发布时间】:2022-06-11 15:54:41
【问题描述】:

我需要测试以下使用我的自定义钩子的组件。

import { useMyHook } from 'hooks/useMyHook';

const MyComponent = () => {
  const myHookObj = useMyHook();
  const handler = () => {
    myHookObj.myMethod(someValue)
  }
  return(
    <button onClick={handler}>MyButton</button>
  );
};

这是我的测试文件:

jest.mock('hooks/useMyHook', () => {
  return {
    useMyHook: () => {
      return {
        myMethod: jest.fn(),
      };
    },
  };
});

describe('<MyComponent />', () => {

  it('calls the hook method when button is clicked', async () => {

    render(<MyComponent {...props} />);

    const button = screen.getByText('MyButton');
    userEvent.click(button);

    // Here I need to check that the `useMyHook.method`
    // was called with some `value`
    // How can I do this?

  });

});

我需要检查 useMyHook.method 是否被一些 value 调用。

我还想从多个it 案例中对其进行测试,并且可能在每次测试中使用不同的值调用它。

我该怎么做?

【问题讨论】:

    标签: reactjs react-hooks jestjs mocking react-testing-library


    【解决方案1】:

    这就是我能够做到的:

    import { useMyHook } from 'hooks/useMyHook';
    
    // Mock custom hook that it's used by the component
    
    jest.mock('hooks/useMyHook', () => {
      return {
        useMyHook: jest.fn(),
      };
    });
    
    // Mock the implementation of the `myMethod` method of the hook
    // that is used by the Component
    
    const myMethod = jest.fn();
    (useMyHook as ReturnType<typeof jest.fn>).mockImplementation(() => {
      return {
        myMethod: myMethod,
      };
    });
    
    // Reset mock state before each test
    // Note: is needs to reset the mock call count
    
    beforeEach(() => {
      myMethod.mockReset();
    });
    

    然后,在 it 子句中,我可以:

    it (`does whatever`, async () => {
      expect(myMethod).toHaveBeenCalledTimes(1);
      expect(myMethod).toHaveBeenLastCalledWith(someValue);  
    });
    

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2017-12-15
      • 1970-01-01
      • 2020-03-20
      • 2020-12-10
      • 2021-12-03
      • 2021-04-17
      • 2020-06-05
      • 2020-09-16
      相关资源
      最近更新 更多