How to mock third party React Native NativeModules

2019-04-09 10:26发布

问题:

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?

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

回答1:

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);