From e1d8891a73bc1b42a9ed64cdc6ead1981e680215 Mon Sep 17 00:00:00 2001 From: Augustin Husson Date: Wed, 8 Sep 2021 17:24:54 +0200 Subject: [PATCH] add global mock for the matchMedia function Signed-off-by: Augustin Husson --- web/ui/react-app/src/hooks/useMedia.ts | 2 +- web/ui/react-app/src/setupTests.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/web/ui/react-app/src/hooks/useMedia.ts b/web/ui/react-app/src/hooks/useMedia.ts index e0c8495ff3..7d542987a0 100644 --- a/web/ui/react-app/src/hooks/useMedia.ts +++ b/web/ui/react-app/src/hooks/useMedia.ts @@ -9,7 +9,7 @@ const useMedia = (query: string): boolean => { const handler = () => setMatches(mediaQuery.matches); mediaQuery.addEventListener('change', handler); return () => mediaQuery.removeEventListener('change', handler); - }, []); + }, [mediaQuery]); return matches; }; diff --git a/web/ui/react-app/src/setupTests.ts b/web/ui/react-app/src/setupTests.ts index 83dd83adfb..f4d3d39b61 100644 --- a/web/ui/react-app/src/setupTests.ts +++ b/web/ui/react-app/src/setupTests.ts @@ -10,6 +10,22 @@ const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock; customGlobal.fetch = require('jest-fetch-mock'); customGlobal.fetchMock = customGlobal.fetch; +// https://stackoverflow.com/questions/39830580/jest-test-fails-typeerror-window-matchmedia-is-not-a-function +// https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom +Object.defineProperty(window, 'matchMedia', { + writable: true, + value: jest.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: jest.fn(), // Deprecated + removeListener: jest.fn(), // Deprecated + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + dispatchEvent: jest.fn(), + })), +}); + // CodeMirror in the expression input requires this DOM API. When we upgrade react-scripts // and the associated Jest deps, hopefully this won't be needed anymore. document.getSelection = function () {