测试历史.使用Jest阻塞函数回调

llmtgqce  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(65)

我实现了一个使用history.block API的自定义提示对话框(请参阅其文档here)。

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

6pp0gazn

6pp0gazn1#

你可能不得不嘲笑历史。block()
在您的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);

字符串
我没有使用过那个API。所以我不确定history是如何实现的。但我认为这应该调用你提供的回调来阻止mockTransition。我希望这能为你指明正确的方向。

相关问题