简体   繁体   中英

testing popstate event with jest

Here is my code:

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

handleBrowserBtn is a function that gets called when user clicks on the browser back button. I'm trying to test this using Jest, but I'm unable to trigger the window.addEventListener('popstate') . Please let me know if there is any way to simulate this using Jest.

Since window is global object, so in our test, we can mock implement the addEventListener and then try invoking the second argument of that mock function.

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

Let me know if you face any issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM