如何模拟第三方React Native NativeModules? [英] How to mock third party React Native NativeModules?

查看:102
本文介绍了如何模拟第三方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() }} />
}

这是react-native-fabricAnswers的相关部分:

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

在摩卡测试中导入此组件时,由于SMXAnswersundefined,因此失败:

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

如何模拟SMXAnswersreact-native-fabric,以使其不会损坏并允许您测试组件?

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

ps:您可以看到完整设置组件我正在尝试在GitHub上进行测试

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

推荐答案

使用mockery模拟任何本地模块,如下所示:

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: () => {},
  },
});

这是完整的设置示例:

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

这篇关于如何模拟第三方React Native NativeModules?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆