用Create React App开玩笑:测试套件无法运行-意外令牌

Ait*_*usi 6 node.js reactjs jestjs create-react-app yarnpkg

开箱即用的带有笑话的create-react-app总是失败

我做过的步骤

create-react-app cra-test
cd cra-test
yarn install
Run Code Online (Sandbox Code Playgroud)

原来testpackage.json变成了

{
  "name": "cra-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-scripts": "1.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject"
  }
}
Run Code Online (Sandbox Code Playgroud)

当我运行yarn test测试失败。这是输出

yarn run v1.1.0
$ jest
FAIL  src\App.test.js
  ? Test suite failed to run

    .../cra-test/src/App.test.js: Unexpected token (7:18)
         5 | it('renders without crashing', () => {
         6 |   const div = document.createElement('div');
      >  7 |   ReactDOM.render(<App />, div);
           |                   ^
         8 |   ReactDOM.unmountComponentAtNode(div);
         9 | });
        10 |

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.413s, estimated 12s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Run Code Online (Sandbox Code Playgroud)

我已经读到这可能是由于升级Jest而导致它与create-react-app不兼容所致,但是我没有这样做。

node --version && yarn --version && npm --version && create-react-app --version
v6.10.2
1.1.0
5.7.1
1.4.3
Run Code Online (Sandbox Code Playgroud)

Evg*_*nko 1

除非你弹出 create-react-app,否则你的根目录中既没有 babel 配置也没有 jest 配置,因此 jest 不知道它必须转译源。所以你必须创建 .babelrc:

{
 "presets": [
   "react-app"
  ]
}
Run Code Online (Sandbox Code Playgroud)

和 jest.config.js:

module.exports = {
  "collectCoverageFrom": [
    "src/**/*.{js,jsx,mjs}"
  ],
  "setupFiles": [
    "<rootDir>/config/polyfills.js"
  ],
  "testMatch": [
    "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
    "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
  ],
  "testEnvironment": "node",
  "testURL": "http://localhost",
  "transform": {
    "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
    "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
    "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
  },
  "transformIgnorePatterns": [
    "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
  ],
  "moduleNameMapper": {
    "^react-native$": "react-native-web"
  },
  "moduleFileExtensions": [
    "web.js",
    "mjs",
    "js",
    "json",
    "web.jsx",
    "jsx",
    "node"
  ]
}
Run Code Online (Sandbox Code Playgroud)

您可以在执行 npm runject 后找到这些配置。

babel-preset-react-app应该安装,因为 jest config 引用了它。另请注意,jest 配置提到了config属于 create-react-app 一部分的目录。这意味着没有它它就无法工作,因此您需要从 create-react-app 复制该目录或编写您自己的设置文件。