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));
    }
  });
5
  • Why would you need to store a function in useRef? (or useState, etc) Commented Nov 3, 2021 at 13:19
  • I need to create a custom hook thats why created like that. Commented Nov 3, 2021 at 14:00
  • Custom hook does not by itself imply storing a function in a ref. Please provide detail about why you need to store a function in a ref. Especially a ref you never change and don't return. Commented Nov 3, 2021 at 14:02
  • i am using this approach. for reference please see link. 30secondsofcode.org/react/s/use-unload Commented Nov 3, 2021 at 14:21
  • 1
    My apologies, that looks legit. In the future please include information like that in the question itself. Commented Nov 3, 2021 at 15:03

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.