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'
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>>' });
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' });
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`
);
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:'
);
});
That's pretty much it, I hope it helps someone ;)
Top comments (0)