diff --git a/package.json b/package.json index 23259543..986595ce 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "file-saver": "^2.0.5", "jszip": "^3.6.0", "license-webpack-plugin": "^2.3.15", + "mq-polyfill": "^1.1.8", "node-sass": "^6.0.1", "prop-types": "^15.7.2", "react": "^16.13.1", diff --git a/src/setupTests.ts b/src/setupTests.ts index 74b1a275..6d49337e 100644 --- a/src/setupTests.ts +++ b/src/setupTests.ts @@ -3,3 +3,18 @@ // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom/extend-expect'; +// @ts-expect-error no typings +import matchMediaPolyfill from 'mq-polyfill'; + +//https://stackoverflow.com/a/66515427/1976323 +matchMediaPolyfill(window); + +// implementation of window.resizeTo for dispatching event +window.resizeTo = function resizeTo(width, height) { + Object.assign(this, { + innerWidth: width, + innerHeight: height, + outerWidth: width, + outerHeight: height, + }).dispatchEvent(new this.Event('resize')); +}; diff --git a/src/utils/os.test.ts b/src/utils/os.test.ts index 6e6be02d..90c3d947 100644 --- a/src/utils/os.test.ts +++ b/src/utils/os.test.ts @@ -3,6 +3,10 @@ import { isMacOS, isWindows, prefersDarkMode } from './os'; +afterEach(() => { + jest.resetAllMocks(); +}); + describe('isMacOS', () => { test('is true', () => { jest.spyOn(navigator, 'platform', 'get').mockReturnValue('MacIntel'); @@ -27,17 +31,13 @@ describe('isWindows', () => { describe('prefersDarkMode', () => { test('is true', () => { - window.matchMedia = jest.fn().mockReturnValue({ + jest.spyOn(window, 'matchMedia').mockReturnValue({ matches: true, } as MediaQueryList); expect(prefersDarkMode()).toBeTruthy(); }); test('is false', () => { - // @ts-expect-error 2790 - delete window.matchMedia; - expect(prefersDarkMode()).toBeFalsy(); - - window.matchMedia = jest.fn().mockReturnValue({ + jest.spyOn(window, 'matchMedia').mockReturnValue({ matches: false, } as MediaQueryList); expect(prefersDarkMode()).toBeFalsy(); diff --git a/src/utils/os.ts b/src/utils/os.ts index 0a56d56d..12685d2e 100644 --- a/src/utils/os.ts +++ b/src/utils/os.ts @@ -24,9 +24,5 @@ export function isWindows(): boolean { * @returns: `true` if dark mode should be preferred, otherwise `false`. */ export function prefersDarkMode(): boolean { - if (!window.matchMedia) { - return false; - } - return window.matchMedia('(prefers-color-scheme: dark)').matches; } diff --git a/yarn.lock b/yarn.lock index 0bad6bd4..c5cd9c44 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8165,6 +8165,11 @@ move-concurrently@^1.0.1: rimraf "^2.5.4" run-queue "^1.0.3" +mq-polyfill@^1.1.8: + version "1.1.8" + resolved "https://registry.yarnpkg.com/mq-polyfill/-/mq-polyfill-1.1.8.tgz#c144190b21214bf8d8b099e7e34e6ca2b888dc14" + integrity sha1-wUQZCyEhS/jYsJnn405soriI3BQ= + ms@2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"