Jest遇到了一个带有react-native

时间:2018-09-05 14:59:18

标签: javascript typescript react-native jestjs

所以我试图用Jest和TypeScript在我的React Native应用上编写测试。使用旧的babel版本时,一切正常,但是由于某些项目问题,我们不得不将babel升级到7.0.0。之后,我无法使其正常工作。感谢您的帮助

Jest遇到意外令牌     这通常意味着您正在尝试导入Jest无法解析的文件,例如这不是普通的JavaScript。     默认情况下,如果Jest看到Babel配置,它将使用该配置来转换文件,而忽略“ node_modules”。

/home/levan/work/vabaco-dhp-frontend/packages/dhp-mobile-app/node_modules/react-native-calendar-events/index.ios.js:3     从'react-native'导入{NativeModules};

SyntaxError:意外的令牌导入

package.json:

"dependencies": {
    "react": "16.4.1",
    "react-native": "0.56.0",
    "react-native-calendar-events": "^1.6.1",
    "react-redux": "^5.0.7",
    "react-router": "^4.3.1",
    "react-router-native": "^4.3.0",
    "react-router-redux": "5.0.0-alpha.9",
    "redux": "^4.0.0",
    "redux-api-middleware": "^2.3.0",
    "redux-form": "^7.4.2",
    "redux-thunk": "^2.3.0",
    "urijs": "^1.19.1"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@types/history": "^4.7.0",
    "@types/jest": "^23.3.1",
    "@types/react": "^16.4.13",
    "@types/react-native": "^0.56.17",
    "@types/react-router": "^4.0.30",
    "@types/react-router-native": "^4.2.3",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.4.2",
    "babel-loader": "^8.0.2",
    "babel-preset-react-native": "^5.0.0",
    "jest": "^23.5.0",
    "react-native-typescript-transformer": "^1.2.10",
    "react-test-renderer": "^16.4.2",
    "ts-jest": "^23.1.4",
    "typescript": "^3.0.3"
},


"jest": {
    "preset": "react-native",
    "transform": {
      "^.+\\.ts?$": "ts-jest",
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.js$": "babel-jest"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)?$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "moduleNameMapper": {
      "^.+\\.(css|less|scss)$": "identity-obj-proxy"
    },
    "transformIgnorePatterns": [
      "/node_modules/(?!(react-native|my-project|react-native-button|react-native-calendar-events)/)"
    ]
  }

babelrc:

{
  "presets": ["react-native", ["@babel/preset-env", {"modules": "commonjs"}]],
  "env": {
    "test": {
      "presets": ["react-native", ["@babel/preset-env"]]
    }
  }
}

1 个答案:

答案 0 :(得分:9)

找到了解决方案。在转换中,您应该使用react-native / jest / preprocessor.js而不是babel-jest。

"jest": {
    "preset": "react-native",
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "transform": {
      "^.+\\.ts?$": "ts-jest",
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js" <--- over here
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)?$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "moduleNameMapper": {
      "^.+\\.(css|less|scss)$": "identity-obj-proxy"
    },
    "transformIgnorePatterns": []
}