首页 > 解决方案 > 无法在反应本机应用程序中将 undefined 或 null 转换为对象

问题描述

最近我们将 react-native 从0.59 迁移到 0.63,并更新了所有必需的模块。发布所有测试用例都失败并出现以下错误。供参考添加了所有配置详细信息

 FAIL  src/assets/Icon.test.tsx
 ● Test suite failed to run
   TypeError: Cannot convert undefined or null to object
    at assign (<anonymous>)
  at _extends (node_modules/@babel/runtime/helpers/extends.js:17:19)
  at Object.user:/Users/APP/node_modules/react-native/Libraries/Renderer/shims/ReactNative.js: (node_modules/@testing-library/react-native/dist/preset/mock-modules.js:41:25)
  at Object.<anonymous> (node_modules/react-native/Libraries/Components/Touchable/Touchable.js:17:21)

babel.config.js

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
};

ts.config.js

{
"compilerOptions": {
 "rootDirs": ["src"],
 "outDir": "dist",
 "target": "es2017",
 "lib": ["es2018"],
 "module": "es2015",
 "moduleResolution": "node",
 "types": ["react", "react-native", "jest"],
 "jsx": "react-native",
 "declaration": true,
 "removeComments": true,
 "strict": true,
 "forceConsistentCasingInFileNames": true,
 "noImplicitReturns": true,
 "noUnusedLocals": true,
 "allowSyntheticDefaultImports": true,
 "experimentalDecorators": true,
 "noImplicitAny": false,
 "sourceMap": true
},
"include": ["typings/*.d.ts", "src/**/*"],
"exclude": [
 "dist",
 "ios",
 "node_modules",
 "android",
 "**/__mocks__",
 "**/__tests__",
 "**/*.test.*",
 "**/test-utils",
 "index.js",
 "index.*.js"
 ]
}

jest.config.js

const jestPreset = require('@testing-library/react-native/jest-preset');
const transformNodeModules = ['react-native', 'react-native-svg', 'react-navigation'];
module.exports = {
  preset: '@testing-library/react-native',
  transformIgnorePatterns: [`node_modules/(?!(${transformNodeModules.join('|')})/)`],
  setupFiles: [...jestPreset.setupFiles, '<rootDir>/src/setupTests.js'],
  collectCoverageFrom: ['<rootDir>/src/**/*.{ts,tsx}'],
  coveragePathIgnorePatterns: ['/test-utils/'],
  coverageDirectory: './coverage',
  coverageThreshold: {
   global: {
     branches: 5,
     functions: 5,
     lines: 5,
     statements: 5,
   },
 },
};

包.json

"react-native": "0.63.0"
"jest": "^24.8.0",
"metro-react-native-babel-preset": "0.65.2",
"babel-jest": "^24.8.0",
"babel-loader": "^8.0.4",

标签: reactjsreact-nativejestjsts-jestbabel-jest

解决方案


推荐阅读