From 8d06672f9c9e5defc6d9f19d9c2bc29e525d4945 Mon Sep 17 00:00:00 2001 From: Markus Stange Date: Tue, 9 Nov 2021 13:17:14 -0500 Subject: [PATCH] Make mock WebChannel less invasive. 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. --- src/test/fixtures/mocks/web-channel.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/test/fixtures/mocks/web-channel.js b/src/test/fixtures/mocks/web-channel.js index 2eb492987c..f02e65204d 100644 --- a/src/test/fixtures/mocks/web-channel.js +++ b/src/test/fixtures/mocks/web-channel.js @@ -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) => { @@ -46,6 +51,8 @@ export function mockWebChannel() { if (onMessageToChrome) { onMessageToChrome(JSON.parse(event.detail).message); } + } else { + originalDispatchEvent.call(window, event); } });