react-nativejestjs

Mocking platform detection in Jest and React Native


Some of the code I am trying to test detects the platform, using, e.g.:

import { Platform } from 'react-native';
...

if (Platform.OS === 'android') {
  ...
} else {
  ...
}

Is there a sensible way to mock this with Jest and/or something else, so I can test both branches in one test run?

Or is the smart way to decouple it and put the platform into, e.g., a context variable? Although it always feels restructuring code to make it easier to test is something of a cheat.


Solution

  • This worked for me (Jest 21.2.1, Enzyme 3.2.0):

    jest.mock('Platform', () => {
        const Platform = require.requireActual('Platform');
        Platform.OS = 'android';
        return Platform;
    });
    

    Put it either at the top of your test, or in a beforeAll for example.