[英]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
: 以下是来自
react-native-fabric
的Answers
的相关部分:
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
: 在mocha测试中导入此组件时,
SMXAnswers
undefined
SMXAnswers
, SMXAnswers
失败:
How do you mock SMXAnswers
or react-native-fabric
so that it doesn't break and allows you to test your components? 你如何模拟
SMXAnswers
或react-native-fabric
以便它不会破坏并允许你测试你的组件?
ps: you can see the full setup and the component I'm trying to test on GitHub. ps:你可以看到完整的设置和我试图在GitHub上测试的组件 。
Use mockery
to mock any native modules like so: 使用
mockery
来模拟任何本机模块,如下所示:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.