DEV Community

V
V

Posted on

Testing react-device-detect with React Testing Library and Jest

I needed to use react-device-detect to change a URL with a https protocol to webcal protocol in order to be able to save an ics file to the calendar app when using Chrome on iOs. The implementation was quite straight forward but I ran with the issue of testing this properly. I needed to mock the user's device and browser detected by react-device-detect.

I did this by first importing the package:

import * as reactDeviceDetect from 'react-device-detect'
Enter fullscreen mode Exit fullscreen mode

and then assigning the value I needed for the functions I'm using in my code:

Object.defineProperty(<<theModule>>, '<<the function or value needed>>', { get: () => '<<the value returned>>' });
Enter fullscreen mode Exit fullscreen mode

This will return the desired value whenever your component calls for the specified function.

In my case, I needed to get true when calling isIOS and 'Chrome' when calling browserName:

import * as reactDeviceDetect from 'react-device-detect';

Object.defineProperty(reactDeviceDetect, 'isIOS', { get: () => true });
Object.defineProperty(reactDeviceDetect, 'browserName', { get: () => 'Chrome' });
Enter fullscreen mode Exit fullscreen mode

Next, to check if my protocol change was working properly, I could either check the href of the a tag as in:

const calendarLink = getByTestId('calendar-link');

expect(calendarLink.closest('a')).toHaveAttribute(
   'href',
   `/my-calendar.ics`
);
Enter fullscreen mode Exit fullscreen mode

or I could fire the click and then check the protocol using the window:

const calendarLink = getByTestId('calendar-link');
fireEvent.click(calendarLink);
await waitFor(() => {
  expect(window.location.protocol).toBe(
    'webcal:'
  );
});
Enter fullscreen mode Exit fullscreen mode

That's pretty much it, I hope it helps someone ;)

Top comments (0)