如何解决如何在RN中模拟本机模块
我尝试在react-native中模拟NativeModules
模块。
为避免每次测试时复制和粘贴,我尝试创建一个“ 模拟 /react-native.js”文件,在此文件中模拟该模块。我发现本教程可以帮上忙,但不起作用https://altany.github.io/react-native/0.61/jest/mocking/upgrade/2020/01/25/mocking-react-native-0.61-modules-with-jest.html
这是我的模拟文件
import * as ReactNative from 'react-native';
export const NativeModules = {
...ReactNative.NativeModules,SettingsManager: {
settings: {
AppleLocale: 'en_US',},};
export const Platform = {
...ReactNative.Platform,OS: 'ios',Version: 123,isTesting: true,select: (objs) => objs.ios,};
export const keyboardDismiss = jest.fn();
export const Keyboard = {
dismiss: keyboardDismiss,};
export default Object.setPrototypeOf(
{
NativeModules,Platform,Keyboard,ReactNative,);
这是产生的错误:
TypeError: Cannot read property 'create' of undefined
1 | import {StyleSheet} from 'react-native';
2 |
> 3 | export default StyleSheet.create({
TypeError: Cannot read property 'get' of undefined
您知道使用模拟文件模拟NativeModules
模块的另一种方法吗?
要么
您知道如何解决这些错误吗?
解决方法
该模拟应该定义*
导入,而不是default
。 ES模块*
导出cannot be defined programmatically。
这应该通过使用CommonJS模块来完成,并且不需要通过原型继承来做到这一点:
const ReactNative = require('react-native');
...
module.exports = {
...ReactNative,__esModule: true,NativeModules,Platform,Keyboard,};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。