I'm attempting to switch my react native application over from using Mocha/Chai to Jest but I'm running into an issue.
Previously in my test/setup.js
I had something along the lines of:
const NativeModules = require('react-native-mock-render').NativeModules;
const MockRNDeviceInfo = require('./support/mock-device-info.js').MockRNDeviceInfo;
NativeModules.RNDeviceInfo = MockRNDeviceInfo;
This however doesn't work with jest as I get the following error when attempting to test one of my components:
TypeError: Cannot read property 'appVersion' of undefined
at Object.getVersion (node_modules/react-native-device-info/deviceinfo.js:39:20)
What is the proper way to set values on NativeModules
?
Setup Run yarn test to run tests with Jest. If you are upgrading your react-native application and previously used the jest-react-native preset, remove the dependency from your package. json file and change the preset to react-native instead.
In Jest you can mock modules using something like:
jest.mock('react-native-device-info', () => {
return {
getVersion: () => 4
}
})
I've only mocked the getVersion
method and returned a random number, since that's the one that is failing for you, but you might have to add the ones you're using in your application (and change the value to the one you want).
You can also use the jest.fn util to mock the functions of the module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With