Search code examples
javascriptreactjsunit-testingjestjsnavigator

How to mock navigation.userAgentData.platform with Jest


I'm trying to mock navigation.userAgentData.platform for a specific computer type. Let's say the computer I'm testing with is a Windows PC and the computer I want to test for is a macOS. Here is an example of the type of situation...

Code:

const MyComponent = () => {
    useEffect(() => {
        if (navigator.userAgentData?.platform === 'macOS') {
            return;  
        } else {
            // do something 
        }
    }, []);

    // ...
}

How would you go about mocking/duplicating navigator.userAgentData?.platform for a unit test?

Usually I would mock with Jest but navigator.userAgentData.platform isn't a function or component I can mock. because it is the computer being used, I assume it will always be the computer I'm using to run the test. I need to specify that a specific computer type is being used for a positive and negative test.


Solution

  • This is a good related solution for this case: https://vincent-benoit.medium.com/how-to-test-useragent-with-jest-inside-a-react-application-cfd87648843a

    Basically, mock userAgentData in test setup and set as needed within the tests.

    Example:

    1. In your Jest setup script:
        Object.defineProperty(window.navigator, 'userAgentData', ((value) => ({
            get() { return value; },
            set(v) { value = v; }
        }))(window.navigator.userAgentData));
    
    1. In your tests:
    it('should do something', () => {
        ...setup...
        global.navigator.userAgentData = { platform: 'macOS' };
        ...get result...
        ...assert...
    });