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.
Maybe the problem in the "import" method, check this:
with "import" this will not work, need to use "require".
React Native 0.61 update
Though the accepted solution works for versions of React Native 0.60 and below, React Native 0.61 has dropped Haste support and this gives an error.
I was able to mock platform detection following the implementation described in this blog post.
Practically, according to the React team, we now have to mock the react-native interface. So, you can create a
react-native.js
file inside thetests/__mocks__
folder and add this code to mock Platform:With this implementation, we can now simply overwrite the OS before running the test like:
This worked for me (Jest 21.2.1, Enzyme 3.2.0):
Put it either at the top of your test, or in a
beforeAll
for example.this is the mock you need:
with it you can do the following:
That way you can have tests for both platforms
OS can be set directly for each test
You have to mock the module and import it into your test. Then you can use
mockImplementation
to set the it to eitherandroid
orios