0

这是我的代码:

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

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

4

1 回答 1

1

由于 window 是全局对象,所以在我们的测试中,我们可以模拟实现 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

如果您遇到任何问题,请告诉我。

于 2019-08-23T05:45:34.363 回答