Categories
JavaScript Answers

How to mock platform detection in Jest and React Native?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *