fahrradflucht
fahrradflucht

Reputation: 1585

How to set the platform on a per test basis for jest tests?

I'm testing react-native components with jest and I often use things like this in my styles:

import { StyleSheet, Platform } from 'react-native';

export default StyleSheet.create({
  container: {
    paddingTop: Platform.OS === 'ios' ? 30 : 10,
  }
});

The problem I'm having is that in the jest tests Platform.OS is always 'ios' which means that the android branch doesn't get tested.

This lets me think that I could maybe change this through a jest config but since I don't want to change it globally but on a per test basis this doesn't make sense anyway.

Upvotes: 5

Views: 3654

Answers (2)

Evan Bacon
Evan Bacon

Reputation: 731

You'll need to mock out each platform using the haste property of your Jest preset. I'd recommend using jest-expo which extends the default React Native Jest preset and runs the tests multiple times, each with a different platform.

disclaimer: I added this functionality to jest-expo when I encountered the same issue.

Upvotes: 1

Turnipdabeets
Turnipdabeets

Reputation: 6005

Try adding this to the top of your test file.

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

You might need to make a different file for iOS, but which ever platform you set in the mock will work for your test spec file.

Upvotes: 2

Related Questions