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

后端 未结 5 636
陌清茗
陌清茗 2021-02-07 04:24

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 { Ap         


        
相关标签:
5条回答
  • 2021-02-07 04:44

    Jest is a JavaScript testing tool, it won't run code that you have written in Objective C/Swift/Java in a native module. You can mock the functionality of a native module so that you can call it from JavaScript by the approach you linked to. eg.

    jest.mock('NetInfo', () => {
      return {
        isConnected: {
          fetch: () => {
            return new Promise((accept, resolve) => {
              accept(true);
            })
          }
        }
      }
    });
    
    0 讨论(0)
  • 2021-02-07 04:44

    This failed for me, too (react-native 0.57.5, jest 23.6.0). I was able to find a solution, but it was totally different (and in my case, a more elegant fix) than here.

    Check out the ticket I filed for more details.

    Essentially, I had to have NativeModules fleshed out by a function passed as the second parameter to jest.mock() and put this is in a script run at the beginning of each test using Jest's setupFiles config option.

    0 讨论(0)
  • 2021-02-07 05:02

    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

    0 讨论(0)
  • 2021-02-07 05:04

    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() } 
      });
      ...
    });
    
    0 讨论(0)
  • 2021-02-07 05:05
    #__mocks__/react-native-modules
    
    const ReactNative = require('react-native')
    
    ReactNative.NativeModules = {
      Defaults: {
        RU: {
          publicKey: '',
          privateKey: '',
        },
      },
    }
    
    module.exports = ReactNative
    

    and then

    # in test file
    jest.mock('react-native-modules')
    import 'react-native-modules'
    
    0 讨论(0)
提交回复
热议问题