【发布时间】: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