Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 623
fahrradflucht Avatar asked Oct 30 '22 17:10

fahrradflucht


1 Answers

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.

like image 75
Turnipdabeets Avatar answered Nov 02 '22 22:11

Turnipdabeets