【问题标题】:Mocking a Native Module when testing with Jest使用 Jest 进行测试时模拟本机模块
【发布时间】:2017-02-13 21:38:40
【问题描述】:

我正在尝试为我的应用程序编写测试,但目前出现以下错误:

● Test suite failed to run

TypeError: Cannot read property 'language' of undefined

  at Object.<anonymous> (node_modules/react-native-localization/LocalizedStrings.js:17:35)

似乎错误是由React-Native-Localization 中检索设备语言环境的这一行引起的:

var localization = require('react-native').NativeModules.ReactLocalization;
var interfaceLanguage = localization.language.replace(/_/g,'-');

该包在wrapper 中使用,该wrapper 将翻译后的字符串返回给组件,因此不会直接调用该包。它看起来像这样:

组件:

import wrapper from '../wrapper'

class component extends Component {
  render() {
    return(
      <Text>{wrapper.getString(key)}</Text>
    );
  }      

  // ...
}

包装器:

import LocalizedStrings from 'react-native-localization'

class wrapper {

  constructor() {
    this.translations = new LocalizedStrings( ... );
  }

  getString(key) {
    return eval(`this.translations.${key}`);
  }

  // ...
}

反应本地化:

var localization = require('react-native').NativeModules.ReactLocalization;
var interfaceLanguage = localization.language.replace(/_/g,'-');

class LocalizedStrings {
  // ...
}

localization 变量设置在类之外,尝试像这样设置变量对我不起作用并返回相同的错误:

jest.mock('react-native-localization', () => {
  // This doesn't work
  const localization = { language: "en-US" }

  // This doesn't work either, because it hits the var initialization
  const rnl = require.requireActual('react-native-localization')
  rnl.localization = { language: "en-US" }

  // ...
})

有人知道如何模拟这个反应原生模块吗?

【问题讨论】:

    标签: testing react-native jestjs


    【解决方案1】:

    由于您正在测试依赖于wrapper 的组件,您可以改为mock wrapper 并让getString() 返回一些您可以在测试中使用的string。这样您就不会使用依赖于其他库的实际 wrapper 类。

    【讨论】:

    • 这就是我害怕的。我不想mock wrapper 因为wrapper 类中的很多东西实际上都被使用了,这意味着我对mock 也有很多好处。谢谢。
    【解决方案2】:

    尝试改用var localization = require('react-native').NativeModules.I18nManager;

    【讨论】:

    猜你喜欢
    • 2019-09-01
    • 2021-08-27
    • 2018-08-29
    • 2017-10-28
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2018-12-14
    相关资源
    最近更新 更多