Code below that I need to test -
const [item, setItem] = useState(() => {
let initialItem = 'both';
if (typeof window !== 'undefined') {
if (window.matchMedia('(max-width: 1012px)').matches) {
initialItem = 'signup';
} else if (window.matchMedia('(max-width: 1460px)').matches) {
initialItem = 'info';
}
}
return initialItem;
});
if (typeof window !== 'undefined') {
window.matchMedia('(max-width: 1012px)').addEventListener('change', (event) => {
if (event.matches) {
setItem('signup');
}
});
window.matchMedia('(max-width: 1460px)').addEventListener('change', (event) => {
if (event.matches) {
setItem('info');
}
});
window.matchMedia('(min-width: 1460px)').addEventListener('change', (event) => {
if (event.matches) {
setItem('both');
}
});
}
I am struggling to test this. This is what I have at the moment -
test('should update layout on window resize', () => {
window.matchMedia = jest.fn().mockImplementation((query) => ({
matches: query !== '(max-width: 1011px)',
media: '',
onchange: null,
addEventListener: jest.fn(),
removeListener: jest.fn(),
}));
globalThis.innerWidth = 1500;
renderTestComponent();
expect(screen.getByTestId('item')).toHaveTextContent('both');
// Resize the window to small
globalThis.innerWidth = 1000;
globalThis.dispatchEvent(new Event('change'));
expect(screen.getByTestId('item')).toHaveTextContent('box');
How can I test that the correct item is shown when the screen changes sizes. Especially with using matchMedia?