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.
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.
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.
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() } }); ... });
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
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