【问题标题】:use jest mockImplementation to mock customized hook in typescript使用 jest mockImplementation 在 typescript 中模拟自定义钩子
【发布时间】:2021-08-04 13:09:56
【问题描述】:

我有一个组件使用一个定制的钩子,我需要编写一些测试并确保我模拟了钩子。如何模拟自定义的钩子以对我的组件进行单元测试,就像钩子的代码甚至不存在一样?

import "./styles.css";
import useAPICall from "@src/hooks/useAPICall ";

export default function App() {
  const { onAPICall } = useAPICall(123);
  const handleOnClick = useCallback(() => {
    onAPICall();
  });

  return (
    <div className="App">
      <button onClick={handleOnClick}>Click</button>
    </div>
  );
}
///test.tsx all I know is this. but I am not sure how I can use mockImplementation that does not return anything
jest.mock('@src/hooks/useAPICall', () => ({
  onAPICall: () => jest.fn(),
}));

【问题讨论】:

    标签: javascript typescript unit-testing jestjs


    【解决方案1】:

    您可以通过三个简单的步骤来完成:

    • 导入要模拟的模块
    • 然后模拟模块
    • 提供模拟模块的返回值。
    import React from 'react';
    import { render } from '@testing-library/react';
    import userEvent from '@testing-library/user-event';
    import App from './App';
    import useAPICall from "@src/hooks/useAPICall "; // 1st step
    
    jest.mock('@src/hooks/useAPICall'); //2nd step
    
    test('can call useAPICall hook', () => {
      useAPICall.mockReturnValue({ onAPICall: jest.fn() }); // 3rd step
      const { getByRole } = render(<NewApp />);
      userEvent.click(getByRole('button'));
      expect(useAPICall).toBeCalled();
    });
    
    

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 2021-04-17
      • 2022-06-17
      • 2021-05-11
      • 2020-08-15
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多