1

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. I don't know how to pass a function to a hook in unit test. I am a beginner.

How can I achieve a 100% coverage for my unit test?

useBrowserFwdBackButton.ts (file in which custom hook is available)

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)

useBrowserFwdBackButton((e) => {
    e.preventDefault();
    if (attachmentListLength !== 0) {
      dispatch(deleteGoogleDocument(attachmentList));
    }
  });
halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

0

Assuming you are using jest and @testing-library/react-hooks for hook testing

you can creat mock function with jest.fn() eg.

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

Yichz
  • 9,250
  • 10
  • 54
  • 92