testing - 使用 Jest 进行测试时模拟 native 模块

标签 testing react-native jestjs

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

● 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,'-');

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

组件:

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}`);
  }

  // ...
}

React-Native-本地化:

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" }

  // ...
})

有谁知道如何模拟这个 React Native 模块?

最佳答案

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

关于testing - 使用 Jest 进行测试时模拟 native 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39874022/

相关文章:

react-native - 如何在渲染函数中调用函数?

reactjs - enzyme 无法通过构造函数选择器找到,但通过显示名称选择器成功找到

javascript - 我如何用 Jest 配置jsdom

ruby-on-rails - 如何只测试重定向到的 URL 的一部分(使用 assert_redirected_to)?

java - Google Foobar Challenge Doomsday Fuel 的隐藏测试用例未通过

Iphone 应用程序测试错误 - STComposeString 和 SenTestCase 错误

node.js - 使用 server.inject 错误捕获的 hapijs 测试

ios - 如何判断用户何时回答了 React-Native 中的 iOS 通知权限请求

android - react-native android url 图像不显示

reactjs - Jest 问题 - ReactElement.js : Failed to get mock metadata