Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a React Native component that imports a custom native module with Jest?

Tags:

Here is a simple component that I am trying to test using React Native 0.39 and Jest 18:

// index.ios.js  import React, { Component } from 'react'; import { AppRegistry, NativeModules, View } from 'react-native';  export default class TestProject extends Component {   componentDidMount() {     NativeModules.TestModule.test();   }    render() {     return <View style={{ flex: 1 }} />;   } }  AppRegistry.registerComponent('TestProject', () => TestProject); 

Here is TestModule and its test method:

// ios/TestProject/TestModule.m  #import "TestModule.h"  @implementation TestModule  RCT_EXPORT_MODULE();  RCT_EXPORT_METHOD(test){   NSLog(@"This is a test"); }  @end 

The following test fails with the error TypeError: Cannot read property 'test' of undefined:

// __tests__/index.ios.js  import 'react-native'; import renderer from 'react-test-renderer'; import React from 'react'; import Index from '../index.ios.js';  it('renders correctly', () => {   const tree = renderer.create(     <Index />   ); }); 

I have read the Jest docs on how to Mock native modules using jest.mock, but am still unclear as to how to extend Jest's mock of NativeModules to include my TestModule class above.

like image 263
andybangs Avatar asked Dec 27 '16 06:12

andybangs


People also ask

How do you test react-native components using Jest?

Setup​ Note: 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. Run yarn test to run tests with Jest.

Can you test react hooks with Jest?

Testing React Hooks with Jest and Enzyme. Jest and Enzyme are tools used for testing React apps. Jest is a JavaScript testing framework used to test JavaScript apps, and Enzyme is a JavaScript testing utility for React that makes it easier to assert, manipulate, and traverse your React components' output.


2 Answers

You can simply add a mock where your native module should be:

import {   NativeModules, } from 'react-native'; import React from 'react'; import renderer from 'react-test-renderer';  describe('TestProject', () => {   beforeEach(() => {     NativeModules.TestModule = { test: jest.fn() }    });   ... }); 
like image 143
rgoldfinger Avatar answered Sep 20 '22 16:09

rgoldfinger


This way, you will mock it once (before jest starts)

jest.config.js

module.exports = {   preset: 'react-native',   setupFiles: ['./__mocks__/your-native-bridge.js'] }; 

__mocks__/your-native-bridge.js

import {NativeModules} from 'react-native';  NativeModules.YourNativeBridge = {   property: jest.fn() }; 

Don't forget to mock all possible functions, properties in YourNativeBridge

like image 23
gr3g Avatar answered Sep 21 '22 16:09

gr3g