简体   繁体   English

在 jest React.js 中编写单元测试时如何将函数传递给自定义钩子

[英]How to pass function to a custom hook while writing unit test in jest React.js

I am facing problem like i have to write a unit test of a custom hook used in index.js see this implementation in which i am passing a function as a parameter.我面临的问题是,我必须编写index.js 中使用的自定义钩子的单元测试,请参阅此实现,其中我将函数作为参数传递。 So i don't know how to pass a function to a hook in unit test.所以我不知道如何在单元测试中将函数传递给钩子。 I am a new bie.我是新手。 I need a urgent help to achieve a 100% coverage for my unit test.我需要紧急帮助来实现单元测试的 100% 覆盖率。

useBrowserFwdBackButton.ts (File in which custom hook is available) 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 (from where hook is calling from functional component) index.js (钩子从功能组件调用的地方)

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

Assuming you are using jest and @testing-library/react-hooks for hook testing假设您使用 jest 和@testing-library/react-hooks进行钩子测试

you can creat mock function with jest.fn() eg.您可以使用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);

additional info (trigger window event) How to trigger a window event during unit testing using vue-test-utils附加信息(触发窗口事件) 如何在使用 vue-test-utils 进行单元测试期间触发窗口事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM