javascript - 如何模拟第三方 React Native NativeModules?

标签 javascript unit-testing react-native mocha.js

组件正在导入包含 native 模块的库。这是一个人为的例子:

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;

在 mocha 测试中导入此组件时,由于 SMXAnswersundefined 而失败:

您如何模拟 SMXAnswersreact-native-fabric 以便它不会损坏并允许您测试您的组件?

p.s.: 你可以看到 full setupcomponent我正在尝试在 GitHub 上进行测试。

最佳答案

使用 mockery 模拟任何原生模块,如下所示:

import mockery from 'mockery';

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

这是一个完整的 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);

关于javascript - 如何模拟第三方 React Native NativeModules?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38292512/

相关文章:

javascript - 如何迭代 Google Analytics 配置文件 ID?

unit-testing - 使用 Vue test-utils 和 jest 测试特定输入元素的值

unit-testing - 使用已经测试过的方法的单元测试方法

javascript - 如何获得 CSS 转换以应用于 React 动态生成的样式?

javascript - v8 JavaScript 对 const、let 和 var 的性能影响?

javascript - 如何在没有嵌套导航的情况下进行导航

react-native - React Navigation - goBack() 会自动调用堆栈导航器屏幕

react-native - 当抽屉打开时 react 抽屉导航导航器移动主要内容

javascript - Modernizr.load 的使用

node.js - 模拟 Node.js 中测试的特定读取文件错误