【问题标题】:How to pass function to a custom hook while writing unit test in Jest/React在 Jest/React 中编写单元测试时如何将函数传递给自定义钩子
【发布时间】:2021-12-17 20:51:19
【问题描述】:

我必须为 index.js (see this implementation) 中使用的自定义钩子编写单元测试,其中我将函数作为参数传递。我不知道如何在单元测试中将函数传递给钩子。我是初学者。

如何实现单元测试 100% 的覆盖率?

useBrowserFwdBackButton.ts(自定义挂钩可用的文件)

import React from 'react';
    
    const useBrowserFwdBackButton = (fn: any) => {
      const cb = React.useRef(fn); // init with fn, so that type checkers won't assume that current might be undefined
    
      React.useEffect(() => {
        cb.current = fn;
      }, [fn]);
    
      React.useEffect(() => {
        const onForwardBackButtonEvent = (...args: any[]) => cb.current?.(...args);
    
        window.addEventListener('popstate', onForwardBackButtonEvent);
    
        return () => window.removeEventListener('popstate', onForwardBackButtonEvent);
      }, []);
    };
    
    export default useBrowserFwdBackButton;

index.js(从函数组件调用钩子的地方)

useBrowserFwdBackButton((e) => {
    e.preventDefault();
    if (attachmentListLength !== 0) {
      dispatch(deleteGoogleDocument(attachmentList));
    }
  });

【问题讨论】:

  • 为什么需要在useRef 中存储一个函数? (或useState等)
  • 我需要创建一个自定义钩子,这就是为什么要这样创建。
  • 自定义钩子本身并不意味着将函数存储在引用中。请提供有关为什么需要将函数存储在 ref 中的详细信息。尤其是你永远不会改变也不会返回的裁判。
  • 我正在使用这种方法。供参考,请参阅链接。 30secondsofcode.org/react/s/use-unload
  • 我很抱歉,这看起来是合法的。将来请在问题本身中包含类似的信息。

标签: javascript reactjs react-hooks jestjs enzyme


【解决方案1】:

假设您使用 jest 和 @testing-library/react-hooks 进行挂钩测试

您可以使用jest.fn() 创建模拟函数 例如。

const mockFunction = jest.fn();
const { result } = renderHook(() => useBrowserFwdBackButton(mockFunction));
const { .... } = result.current;

// since it's attached to windows event, you need to trigger the "popstate" event

// expects here
expect(mockFunction).toBeCalledTimes(1);

附加信息(触发窗口事件)How to trigger a window event during unit testing using vue-test-utils

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 2021-03-10
    • 2021-06-07
    • 1970-01-01
    • 2021-04-17
    • 2019-04-06
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多