我正在尝试为我的应用程序编写测试,但目前出现以下错误:
● 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/