Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed an issue in chapter 6 where window repeatedly listened to popstate event. #26

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

cxc421
Copy link

@cxc421 cxc421 commented Apr 11, 2022

In the section 6.4.2 of the book it is written:

When using detachPopstateHandlers in main.test.js, you must be careful when detaching all of the window’s listeners after each test, because, otherwise, the listener attached by main.js can accidentally be detached, too. To avoid removing the listeners attached by main.js, make sure that you spy on window.addEventListener only after executing main.js

The current code looks like this:

beforeEach(() => {
  document.body.innerHTML = initialHtml;

  // You must execute main.js again so that it can attach the
  // event listener to the form every time the body changes.
  // Here you must use `jest.resetModules` because otherwise
  // Jest will have cached `main.js` and it will _not_ run again.
  jest.resetModules();
  require("./main");

  // You can only spy on `window.addEventListener` after `main.js`
  // has been executed. Otherwise `detachPopstateHandlers` will
  // also detach the handlers that `main.js` attached to the page.
  jest.spyOn(window, "addEventListener");
});

afterEach(detachPopstateHandlers);

But this is a bit strange, currently detachPopstateHandlers will only detach the popstate event registered in the test, but each time beforeEach will re-execute main.js so the window will also register the popstate event again but without first removing the previous registration? So I think we should spy on window.addEvenetListener before main.js has been executed.

I wrote a test based on the current implementation to verify this problem, this program simply prints out where popstate event is triggered, and after execution, it can be found that window has registered the popstate event multiple times.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant