Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ReactNative's NativeModules.RNDeviceInfo with Jest

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?

like image 318
Kyle Decot Avatar asked Apr 25 '17 11:04

Kyle Decot


People also ask

How do you test react native components using Jest?

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.


1 Answers

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.

like image 124
Preview Avatar answered Sep 25 '22 21:09

Preview