【问题标题】:How mock the native module in RN如何在 RN 中模拟原生模块
【发布时间】:2020-12-26 16:03:50
【问题描述】:

我尝试在 react-native 中模拟模块 NativeModules

为避免在每次测试中复制和粘贴,我尝试创建一个“mocks/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 模块的另一种方法吗? 要么 你知道如何解决这些错误吗?

【问题讨论】:

    标签: javascript reactjs react-native mocking jestjs


    【解决方案1】:

    模拟应该定义* 导入,而不是default。和ES模块*导出cannot be defined programmatically

    这应该通过使用 CommonJS 模块来完成,而原型继承则不需要这样做:

    const ReactNative = require('react-native');
    ...
    module.exports = {
      ...ReactNative,
      __esModule: true,
      NativeModules,
      Platform,
      Keyboard,
    };
    

    【讨论】:

    • 我已经根据您的示例调整了我的模拟,但出现了这个错误。 Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'DevSettings' could not be found. Verify that a module by this name is registered in the native binary.我不明白怎么解决
    • 没有 mock 是否可行?答案解决了 Jest 模拟的问题,我不能保证 RN 可以使用这些模拟,因为它可能需要对 RN 内部有很好的理解才能以正确的方式模拟它。至于报错,好像很常见,stackoverflow.com/questions/59713472/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多