Test history.block function callback with Jest

65 views Asked by At

I implemented a custom Prompt dialog that uses history.block API (see its docs here).

useEffect(() => {
  if (shouldBlock) {
    const unblock = history.block(transition => {
      const navigationUrl = transition.location.pathname;
      console.log('TEST: ', url);
      showPromptDialog(navigationUrl, unblock);
    });
  }
}, [shouldBlock]);

I'm trying to test now if my showPromptDialog function is called, however even the console.log that I put there was not run. How to make a test in a way that I can check if the function (can be even console.log for now) was fired?

My test:

test('block navigation and fire console.log', async () => {
  renderPrompt();

  await userEvent.click(screen.getByText('Route'));

  expect(history.block).toHaveBeenCalled(); // this works

  // Check if console.log was fired
});
1

There are 1 answers

0
Mister_CK On

You will probably have to mock history.block()

in your testFile:

import * as historyModule from 'whereEver/the/history/comes/from'

const mockHistory = {
  block: (callBack) => {
    const mockTransition = {
      location: {
        pathname: '/mock-path',
      },
    };
    callBack(mockTransition);
  }, 
}

jest.spyOn(historyModule, 'createMemoryHistory').mockReturnValue(mockHistory);

I haven't used that api. So I am not sure exactly how history is implemented. But I think this should call the callback you provide to block with the mockTransition. I hope this points you in the right direction.