I’m writing some tests using Jest and React-testing library. In my tests, I’d like to simulate the case in which users have reduced-motion set on their devices.
I tried the following, but it didn’t work:
describe('TestComponent', () => {
it('should make selection with reduced motion preference', async () => {
setReducedMotionPreference(true);
render(<TestApp />);
// open select component, which produces animation
await userEvent.click(screen.getByText('option 2'));
// choose another option from the select options
const option1 = screen.getByTitle('option 1');
await userEvent.click(option1);
// verify that option 1 is selected and option 2 not
expect(option1.classList.contains('ant-select-item-option-selected')).toBeTruthy();
const option2 = screen.getByTitle('option 2');
expect(option2.classList.contains('ant-select-item-option-selected')).toBeFalsy();
});
});
Here’s how the implementation of setReducedMotionPreference
:
const setReducedMotionPreference = value => {
window.matchMedia = jest.fn().mockImplementation(query => {
return {
matches: query === '(prefers-reduced-motion: reduce)' ? value : false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
};
});
};
When I debug, I see that window.matchMedia('(prefers-reduced-motion: reduce)').matches
is true. On the browser (I’ve set reduced motion on my OS) the select (imported from ant-design UI library) component isn’t working as expected, so I expect the test to fail, but it passes.
Am I doing something wrong in the mocking or this is simply not possible to test in JSDOM?