Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { act, render } from '@testing-library/react';

// eslint-disable-next-line import/extensions
import { useMobile } from '../index';
import * as safeMatchMediaModule from '../../utils/safe-match-media';

function Demo() {
const renderCount = useRef(0);
Expand All @@ -21,7 +22,14 @@ function Demo() {

function resizeWindow(width: number) {
act(() => {
Object.defineProperty(window, 'innerWidth', { value: width });
// Mock safeMatchMedia to return the result of a passed-in `max-width` query based on the width the window wasjust resized to
jest.spyOn(safeMatchMediaModule, 'safeMatchMedia').mockImplementation((element, query) => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test code was copied over from the components package, but here it didn't work because the implementation of getIsMobile behaves differenttly in one package vs the other when window.matchMedia is not present:

Fallbacks are not needed because matchMedia has very good browser support: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia#browser_compatibility

// Extract the max-width value from the query
const match = query.match(/max-width:\s*(\d+)px/);
const maxWidth = match ? parseInt(match[1], 10) : Infinity;
return width <= maxWidth;
});

window.dispatchEvent(new CustomEvent('resize'));
});
}
Expand Down
Loading