tests: use matchMedia polyfill

This makes testing code that uses window.matchMedia() work better since
it mocks it globally.
This commit is contained in:
David Lechner
2021-07-02 20:59:09 -05:00
committed by David Lechner
parent fbc4ecadbe
commit c3851e7139
5 changed files with 27 additions and 10 deletions
+1
View File
@@ -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",
+15
View File
@@ -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'));
};
+6 -6
View File
@@ -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();
-4
View File
@@ -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;
}
+5
View File
@@ -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"