用玩笑测试popstate事件

时间:2019-08-22 18:11:19

标签: javascript reactjs jestjs

这是我的代码:

useEffect(() => {
    if (paymentSuccessful)
      window.addEventListener('popstate', handleBrowserBtn);
    return () => 
window.removeEventListener('popstate', handleBrowserBtn);
  }, [paymentSuccessful]);

handleBrowserBtn是当用户单击浏览器的后退按钮时调用的函数。我正在尝试使用Jest进行测试,但是无法触发window.addEventListener('popstate')。请让我知道是否有任何方法可以使用Jest进行模拟。

1 个答案:

答案 0 :(得分:0)

由于窗口是全局对象,因此在我们的测试中,我们可以模拟实现addEventListener,然后尝试调用该模拟函数的第二个参数。

const mockAddEventListener = jest.fn();
  window.addEventListener = mockAddEventListener;
  // do your action here which will trigger useEffect

  // here the first [0] of calls denotes the first call of the mock
  // the second [0] denotes the index of arguments passed to that call
  expect(mockAddEventListener.mock.calls[0][0]).toBe('popstate');

  // so we can trigger handleBrowserBtn by calling [1] index
  mockAddEventListener.mock.calls[0][1]();

// now assert here what was being done in handleBrowserBtn callback

让我知道您是否遇到任何问题。