jest test for a custom hook

Viewed 345

I have created a custom hook to display a notification message and remove it after 2 seconds. I want to write a test for this. I'm new to writing tests and not entirely sure how to write a test for this. Can anyone help me?

my hook

export function useNotification() {
  const dispatch = useDispatch();
  const notifications = useSelector(getNotificationsState);
  function toast(type, message) {
    const id = notifications.toasts.length;
    const data = { type, message, id };
    dispatch({
      type: NOTIFICATION_ACTIONS.ADD_TOAST,
      payload: data,
    });

    setTimeout(() => {
      dispatch({
        type: NOTIFICATION_ACTIONS.REMOVE_TOAST,
        payload: id,
      });
    }, NOTIFICATION_TIMEOUT);
  }

  return toast;
}

I want to write the test for above hook

describe('useNotification', () => {
    //Actual test
});
1 Answers

Hopefully, this snippet can help

import { useSelector, useDispatch } from 'react-redux';

jest.useFakeTimers(); 

const mockedUseDispatch = jest.fn();
const mockedUseSelector = jest.fn();
jest.mock('react-redux', () => ({
  useSelector: mockedUseSelector,
  useDispatch: mockedUseDispatch
}));

describe('useNotification', () => {
    it('Should show and dismiss toast', () => {
       //arrange
       useSelector.mockImplementation((getNotificationsState) => getNotificationsState(yourMockedStoreData));

       //act
       const toast = useNotification()
       toast(type, message) //type, message are your own data

       //assert
       expect(toast).toHaveBeenCallTimes(1)
       expect(toast).toHaveBeenCallWith({
         type: NOTIFICATION_ACTIONS.ADD_TOAST,
         payload: data, //your expected data
       })

      // Fast-forward
      jest.advanceTimersByTime(NOTIFICATION_TIMEOUT);
      
      expect(toast).toHaveBeenCallTimes(2)
      expect(toast).toHaveBeenCallWith({
         type: NOTIFICATION_ACTIONS.ADD_TOAST,
         payload: id, //your expected data
      })
    })
});

Note that I cannot run it with your setup, so I tried to give you the basic understanding about how to implement an unit test for custom hook.

Some references

https://jestjs.io/docs/timer-mocks#advance-timers-by-time

https://dev.to/coderjay06/the-three-a-s-of-unit-testing-b22

Related