使用Jest进行测试时模拟Native模块

时间:2016-10-05 12:30:30

标签: 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,'-');

该包用于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" }

  // ...
})

有谁知道如何模仿这个反应原生模块?

2 个答案:

答案 0 :(得分:0)

由于您正在测试依赖于wrapper的组件,因此您可以mock代替wrapper并让getString()返回string您的wrapper可以在你的测试中使用。这样您就不会使用依赖于其他库的实际<head> <base href="/"> </head> 类。

答案 1 :(得分:-1)

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