简体   繁体   中英

How to mock third party React Native NativeModules?

A component is importing a library that includes a native module. Here is a contrived example:

import React from 'react';
import { View } from 'react-native';
import { Answers } from 'react-native-fabric';

export default function MyTouchComponent({ params }) {
  return <View onPress={() => { Answers.logContentView() }} />
}

And here is the relevant part of Answers from react-native-fabric :

var { NativeModules, Platform } = require('react-native');
var SMXAnswers = NativeModules.SMXAnswers;

When importing this component in a mocha test, this fails on account that SMXAnswers is undefined :

How do you mock SMXAnswers or react-native-fabric so that it doesn't break and allows you to test your components?

ps: you can see the full setup and the component I'm trying to test on GitHub.

Use mockery to mock any native modules like so:

import mockery from 'mockery';

mockery.enable();
mockery.warnOnUnregistered(false);
mockery.registerMock('react-native-fabric', {
  Crashlytics: {
    crash: () => {},
  },
});

Here is a complete setup example :

import 'core-js/fn/object/values';
import 'react-native-mock/mock';

import mockery from 'mockery';
import fs from 'fs';
import path from 'path';
import register from 'babel-core/register';

mockery.enable();
mockery.warnOnUnregistered(false);
mockery.registerMock('react-native-fabric', {
  Crashlytics: {
    crash: () => {},
  },
});

const modulesToCompile = [
  'react-native',
].map((moduleName) => new RegExp(`/node_modules/${moduleName}`));

const rcPath = path.join(__dirname, '..', '.babelrc');
const source = fs.readFileSync(rcPath).toString();
const config = JSON.parse(source);

config.ignore = function(filename) {
  if (!(/\/node_modules\//).test(filename)) {
    return false;
  } else {
    const matches = modulesToCompile.filter((regex) => regex.test(filename));
    const shouldIgnore = matches.length === 0;
    return shouldIgnore;
  }
}

register(config);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM