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
+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;
}