使用 Jest 测试 History.block 函数调用

问题描述 投票:0回答:1

我实现了一个使用

history.block
API 的自定义提示对话框(请参阅其文档此处)。

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

我现在正在尝试测试我的

showPromptDialog
函数是否被调用,但是即使我放在那里的 console.log 也没有运行。如何进行测试以检查该函数(现在甚至可以是
console.log
)是否被触发?

我的测试:

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
});
reactjs jestjs react-testing-library browser-history
1个回答
0
投票

你可能不得不模拟history.block()

在你的测试文件中:

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);

我没用过那个api。所以我不确定历史到底是如何实现的。但我认为这应该调用您提供的回调来阻止mockTransition。我希望这能为您指明正确的方向。

© www.soinside.com 2019 - 2024. All rights reserved.