类型错误:无法读取未定义的属性“语言”

Gha*_*Haq 6 javascript reactjs react-native

我正在尝试运行__test__中的 React Native 提供的App-test.js文件,即

\n\n
import \'react-native\';\nimport React from \'react\';\nimport App from \'../src/app\';\n\n// Note: test renderer must be required after react-native.\nimport renderer from \'react-test-renderer\';\n\nit(\'renders correctly\', () => {\n  renderer.create(<App />);\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

package.json中的 Jest看起来像这样

\n\n
...\n  "jest": {\n    "preset": "react-native",\n    "setupFiles": [\n      "<rootDir>/node_modules/react-native-gesture-handler/jestSetup.js"\n    ],\n    "transformIgnorePatterns": [\n      "node_modules/(?!react-native)/"\n    ],\n    "globals": {\n      "__DEV__": true\n    },\n    "testEnvironment": "node"\n  }\n...\n
Run Code Online (Sandbox Code Playgroud)\n\n

我正在使用包react-native-localization,它在应用程序中工作正常,但在运行笑话时出现错误,即:

\n\n
__tests__/App-test.js\n  \xe2\x97\x8f Test suite failed to run\n\n    TypeError: Cannot read property \'language\' of undefined\n\n       5 | import fr from \'./fr\';\n       6 | \n    >  7 | let localize = new LocalizedStrings({\n         |                ^\n       8 |     en: en,\n       9 |     fr: fr\n      10 | });\n\n      at Object.customLanguageInterface (node_modules/react-native-localization/lib/LocalizedStrings.js:49:23)\n      at LocalizedStrings.call (node_modules/localized-strings/lib/LocalizedStrings.js:67:42)\n      at new LocalizedStrings (node_modules/react-native-localization/lib/LocalizedStrings.js:63:117)\n      at Object.<anonymous> (src/common/language/localizeController.js:7:16)\n      at Object.<anonymous> (src/containers/auth/launchScreen.js:25:1)\n\n  console.error node_modules/fbjs/lib/warning.js:30\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

localizeController.js是

\n\n
import LocalizedStrings from \'react-native-localization\';\n\nimport en from \'./en\';\nimport fr from \'./fr\';\n\nlet localize = new LocalizedStrings({\n    en: en,\n    fr: fr\n});\n\nexport default localize;\n\n
Run Code Online (Sandbox Code Playgroud)\n\n

在launchScreen中像这样使用它

\n\n
import localize from \'@common/language/localizeController\';\n\n...\n\n<Text style={styles.titleText}>{localize.Title}</Text>\n\n...\n
Run Code Online (Sandbox Code Playgroud)\n\n

由于所有组件都使用了此本地化,因此我无法测试任何组件。

\n

Gha*_*Haq 6

创建jest-setup.js文件(如果尚不存在)并在其中添加以下行

import { NativeModules } from 'react-native';

NativeModules.ReactLocalization = {
    language: 'en',
};

Run Code Online (Sandbox Code Playgroud)

现在将其添加到package.json中,现在 package.json 中的 JEST 看起来像这样。

...
"jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|react)/"
    ],
    "setupFiles": [
      "<rootDir>/jest-setup.js"
    ],
    "globals": {
      "__DEV__": true
    },
    "testEnvironment": "node"
  }
...
Run Code Online (Sandbox Code Playgroud)

现在这个错误消失了。 来源