我正在尝试运行 __test__ 中的 react native 提供的 App-test.js 文件,即
import 'react-native';
import React from 'react';
import App from '../src/app';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
开玩笑包.json 看起来像这样
...
"jest": {
"preset": "react-native",
"setupFiles": [
"<rootDir>/node_modules/react-native-gesture-handler/jestSetup.js"
],
"transformIgnorePatterns": [
"node_modules/(?!react-native)/"
],
"globals": {
"__DEV__": true
},
"testEnvironment": "node"
}
...
我正在使用包 react 本地化 这在应用程序中运行良好,但在运行 jest 时出错,即:
__tests__/App-test.js
● Test suite failed to run
TypeError: Cannot read property 'language' of undefined
5 | import fr from './fr';
6 |
> 7 | let localize = new LocalizedStrings({
| ^
8 | en: en,
9 | fr: fr
10 | });
at Object.customLanguageInterface (node_modules/react-native-localization/lib/LocalizedStrings.js:49:23)
at LocalizedStrings.call (node_modules/localized-strings/lib/LocalizedStrings.js:67:42)
at new LocalizedStrings (node_modules/react-native-localization/lib/LocalizedStrings.js:63:117)
at Object.<anonymous> (src/common/language/localizeController.js:7:16)
at Object.<anonymous> (src/containers/auth/launchScreen.js:25:1)
console.error node_modules/fbjs/lib/warning.js:30
本地化 Controller .js 是
import LocalizedStrings from 'react-native-localization';
import en from './en';
import fr from './fr';
let localize = new LocalizedStrings({
en: en,
fr: fr
});
export default localize;
在launchScreen中像这样使用它
import localize from '@common/language/localizeController';
...
<Text style={styles.titleText}>{localize.Title}</Text>
...
如此本地化 用于所有组件,我无法测试任何组件。
最佳答案
创建 jest-setup.js 文件(如果不存在)并在其中添加以下行
import { NativeModules } from 'react-native';
NativeModules.ReactLocalization = {
language: 'en',
};
现在添加到 包.json ,现在 package.json 中的 JEST 看起来像这样。
...
"jest": {
"preset": "react-native",
"transformIgnorePatterns": [
"node_modules/(?!react-native|react)/"
],
"setupFiles": [
"<rootDir>/jest-setup.js"
],
"globals": {
"__DEV__": true
},
"testEnvironment": "node"
}
...
现在这个错误消失了。
Source
关于javascript - 类型错误 : Cannot read property 'language' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61612609/