Some of the code I am trying to test detects the platform, using, e.g.:
import { Platform } from 'react-native';
...
if (Platform.OS === 'android') {
...
} else {
...
}
Is there a sensible way to mock this with Jest and/or something else, so I can test both branches in one test run?
Or is the smart way to decouple it and put the platform into, e.g., a context variable? Although it always feels restructuring code to make it easier to test is something of a cheat.
For everyone looking for this, what it helped me was the following:
You can mock whatever you want from
React-Native
like this:use jest.doMock and jest.resetModules
The way that I achieved mocking setting the platform was just set it directly in the tests:
This would setup the platform to only run on Android during tests to make sure that my function was calling only specific functions. My function that was wrapped in platform dependent compilation looked like:
I would suggest just creating two different tests one with the platform set to iOS and the other to Android since ideally a function should only have one responsibility. However, I'm sure you can use this to run the first test, dynamically set the platform and run test number two all in one function.
Since the other answers will not work if you want to mock different OSs in the same test suite and in one test run, here's another way. Instead of using
Platform.OS
directly in your code, define a helper function somewhere and use that to get references to the OS in your components:in 'helpers.js':
in your component:
This function can then be mocked it in your tests, e.g.
Credit for the idea goes to this GitHub issue comment.