0
votes

I use isMobileOnly from "react-device-detect" npm package in my React component say(SampleComponent.js).

I would like to customize the return value of isMobileOnly in my jest unit tests.

I have tried Jest manual mocks as mentioned in the link below: https://jestjs.io/docs/en/manual-mocks

But it does not seem to work for me.

I have also tried: jest's mockImplementation jest's mockImplementationOnce jest's spyOn

import {isMobileOnly} from 'react-device-detect;

In my jest unit tests, i would like to mock the function isMobileOnly in such a way that i should be able to customize its return value to "true". The default value is "false".

3

3 Answers

1
votes

Finally! I figured it out myself after hours of struggle. Here is what i did:

  1. Created __mocks__ folder in the same level as node_modules directory where the package "react-device-detect" is available. Note: smaller case is important for __mocks__.
  2. Created a file named "react-device-detect.js" within the __mocks__ folder.
  3. Added the following code in it:

    const deviceDetect = jest.genMockFromModule('react-device-detect');
    deviceDetect.isMobileOnly = true;
    module.exports = deviceDetect;
    
  4. Within the test file, i imported the "isMobileOnly" as i did in the original component:

    import { isMobileOnly } from 'react-device-detect';
    
  5. Now, i can change value of "deviceDetect.isMobileOnly" to true or false in the mocked file as per the unit test case's need .

For more details, refer the official documentation here https://jestjs.io/docs/en/manual-mocks

Thanks @Roman for reaching out!

1
votes

This worked for me.

In your test file, add this: import * as deviceDetect from 'react-device-detect';

then you can change things like: deviceDetect.isMobileOnly = true;

eg.

import * as deviceDetect from 'react-device-detect'; //<--important

it.only('clicking on myAccount redirects to /user/myAccount', () => {

        ///make sure this is before mount or shallow
        deviceDetect.isMobileOnly = true; //<--important

        component = mount(<Provider store={store}><Sidebar history={mockedHistory} /></Provider>);
        component.find('[test-id="myAccount"]').first().simulate('click');
        expect(mockedHistory.push).toHaveBeenCalledWith('/user/myAccount');
    });
0
votes

You can possibly override the User Agent for testing purposes so react-device-detect package will identify it like You need, here's how to do that.

This topic should also be helpful.