Skip to content

Commit

Permalink
Make mock WebChannel less invasive.
Browse files Browse the repository at this point in the history
The WebChannel mocking now calls the original functions for
addEventListener, removeEventListener, and dispatchEvent. This means that
it won't interfere with other uses of these APIs.

One example of such a use is the popstate event: UrlManager.test.js has
a test which makes sure that the URL state is restored when going
backwards in history. Using a mocked WebChannel in that test broke it
because the popstate event was no longer being dispatched.
  • Loading branch information
mstange committed Nov 16, 2021
1 parent 84c3049 commit 8d06672
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/test/fixtures/mocks/web-channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,25 +16,30 @@ import type {
export function mockWebChannel() {
const messagesSentToBrowser = [];
const listeners = [];
const originalAddEventListener = window.addEventListener;
const originalRemoveEventListener = window.removeEventListener;
const originalDispatchEvent = window.dispatchEvent;
let onMessageToChrome = null;

jest
.spyOn(window, 'addEventListener')
.mockImplementation((name, listener) => {
.mockImplementation((name, listener, options) => {
if (name === 'WebChannelMessageToContent') {
listeners.push(listener);
}
originalAddEventListener.call(window, name, listener, options);
});

jest
.spyOn(window, 'removeEventListener')
.mockImplementation((name, listener) => {
.mockImplementation((name, listener, options) => {
if (name === 'WebChannelMessageToContent') {
const index = listeners.indexOf(listener);
if (index !== -1) {
listeners.splice(index, 1);
}
}
originalRemoveEventListener.call(window, name, listener, options);
});

jest.spyOn(window, 'dispatchEvent').mockImplementation((event) => {
Expand All @@ -46,6 +51,8 @@ export function mockWebChannel() {
if (onMessageToChrome) {
onMessageToChrome(JSON.parse(event.detail).message);
}
} else {
originalDispatchEvent.call(window, event);
}
});

Expand Down

0 comments on commit 8d06672

Please sign in to comment.