Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Jest mocking Platform

When writing unit tests for a React Native project I want to be able to test different snapshots based on different platforms.

I first tried jest.mock to mock Platform but seems to be async. This approach does work when I have two separate files, but I'd prefer to keep everything in one file if possible.

I tried jest.doMock because of this snippet from the documentation:

When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior. https://facebook.github.io/jest/docs/en/jest-object.html#jestdomockmodulename-factory-options

However I'm still seeing undesirable results. When I console.log in the android test I see that Platform.OS is whatever I set the first doMock to be.

I also tried wrapping the mock in a beforeEach in a describe becasue I thought that might help with scoping http://facebook.github.io/jest/docs/en/setup-teardown.html#scoping

 describe('ios test', () => {
  it('renders ui correctly', () => {
    jest.doMock('Platform', () => {
      const Platform = require.requireActual('Platform');
      Platform.OS = 'ios';
      return Platform;
    });
    const wrapper = shallow(<SomeComponent />);
    const tree = renderer.create(wrapper).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

describe('android test', () => {
  it('renders ui correctly', () => {
    jest.doMock('Platform', () => {
      const Platform = require.requireActual('Platform');
      Platform.OS = 'android';
      return Platform;
    });
    const wrapper = shallow(<SomeComponent />);
    const tree = renderer.create(wrapper).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

Any ideas on how I can change the mock Platform for tests in the same file?

like image 827
Turnipdabeets Avatar asked Nov 20 '25 04:11

Turnipdabeets


1 Answers

There are a lot of suggestions on how to solve this problem in another question, but none of them worked for me either, given the same requirements you have (tests for different OSs in the same suite file and in one test run).

I eventually worked around it with a somewhat clunky trivial helper function that can be mocked as expected in tests – something like:

export function getOS() {
  return Platform.OS;
}

Use it instead of Platform.OS in your code, and then simply mock it in your tests, e.g.

it('does something on Android', () => {
  helpers.getOS = jest.fn().mockImplementationOnce(() => 'android');
  // ...
}

That did the trick; credit for the idea is due to this guy.

like image 198
d0gb3r7 Avatar answered Nov 22 '25 19:11

d0gb3r7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!