Testing 使用Jest测试时模拟本机模块
我正在尝试为我的应用程序编写测试,但当前出现以下错误:Testing 使用Jest测试时模拟本机模块,testing,react-native,jestjs,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) 该包用于将翻译后的字符串返回给组件的包装器,因此不直接调用该包。它看起来像这样
● Test suite failed to run
TypeError: Cannot read property 'language' of undefined
at Object.<anonymous> (node_modules/react-native-localization/LocalizedStrings.js:17:35)
该包用于将翻译后的字符串返回给组件的包装器
,因此不直接调用该包。它看起来像这样:
组成部分:
import wrapper from '../wrapper'
class component extends Component {
render() {
return(
<Text>{wrapper.getString(key)}</Text>
);
}
// ...
}
反应本地本地化:
var localization = require('react-native').NativeModules.ReactLocalization;
var interfaceLanguage = localization.language.replace(/_/g,'-');
class LocalizedStrings {
// ...
}
本地化
变量是在类之外设置的,尝试这样设置变量对我不起作用,并返回相同的错误:
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本机模块吗?因为您正在测试依赖于
包装器的组件,所以您可以模拟包装器
,让getString()
返回一些可以在测试中使用的字符串。这样,您就不会使用依赖于其他库的实际包装器类。尝试使用var-localization=require('react-native')。NativeModules.I18nManager代码>相反这正是我害怕的。我不想模拟wrapper
,因为wrapper
类中的很多东西都被实际使用了,这意味着我也会有很多好东西来模拟mock
。谢谢。这行代码来自我正在使用的npm包。我宁愿不要用叉子叉它。我知道,但如果你改变这一点,我相信问题已经解决了;)
var localization = require('react-native').NativeModules.ReactLocalization;
var interfaceLanguage = localization.language.replace(/_/g,'-');
class LocalizedStrings {
// ...
}
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" }
// ...
})