How to mock platform detection in Jest and React Native?

Sometimes, we want to mock platform detection in Jest and React Native.

In this article, we’ll look at how to mock platform detection in Jest and React Native.

How to mock platform detection in Jest and React Native?

To mock platform detection in Jest and React Native, we can call jest.mock to mock the Platform module.

For instance, we write:

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

to call jest.mock with 'Platform and a function that return the Platform object.

Before we return it, we set the Platform.OS property to 'android' so Platform.OS would be 'android' in our tests.

Conclusion

To mock platform detection in Jest and React Native, we can call jest.mock to mock the Platform module.