【问题标题】:React tests are not working after building it by Webpack通过 Webpack 构建 React 测试后无法正常工作
【发布时间】:2020-08-13 15:16:24
【问题描述】:

我有一个问题需要花费大量时间来寻求解决方案。 以前我的项目是由 CRA 构建的,并且使用了 react-scripts。测试脚本正在运行。对于测试,我使用了 react-testing-library (现在默认实现反应)。 实际上它已经改变了,现在应用程序是由 webpack 构建的。我试图实现 jest 和测试,但我无法以正确的方式配置它。

我试过了:

  • 安装 jest 和 babel-jest
  • 添加 jest.config.js / jest.config.json

但还是开玩笑给我发了这个信息:


    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.     

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

只要符合 React 语法就会显示错误

it("renders without crashing", () => {
       6 |   const div = document.createElement("div")
    >  7 |   ReactDOM.render(<App/>, div)
         |                   ^
       8 | })

我的 webpack 配置:

let path = require("path")

module.exports = {
  entry: {
    app: "./src/index.js",
  },
  output: {
    filename: "[name].js",
    path: path.resolve(process.cwd(), "name/static/js"),
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"],
          },
        },
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
}

package.json

{
  "name": "app-name",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/user-event": "^7.1.2",
    "axios": "^0.19.2",
    "bootstrap": "^4.4.1",
    "formik": "^2.1.4",
    "json-server": "^0.16.1",
    "lodash": "^4.17.15",
    "react": "^16.13.0",
    "react-input-mask": "^2.0.4",
    "react-simple-timefield": "^3.0.0",
    "reactstrap": "^8.4.1",
    "yup": "^0.28.3"
  },
  "scripts": {
    "test": "jest",
    "start-dev": "webpack --progress --colors --watch --config webpack.dev.js",
    "build": "webpack --progress --colors --config webpack.prod.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version",
      "last 1 edge version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/plugin-transform-react-jsx": "^7.9.4",
    "@babel/preset-env": "^7.9.0",
    "@babel/preset-react": "^7.9.4",
    "@testing-library/dom": "^7.1.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "babel-jest": "^25.5.0",
    "babel-loader": "^8.1.0",
    "css-loader": "^3.4.2",
    "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "jest": "^25.5.0",
    "react-dom": "^16.13.1",
    "react-snapshot": "^1.3.0",
    "react-test-renderer": "^16.13.1",
    "style-loader": "^1.1.3",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11",
    "webpack-merge": "^4.2.2"
  }
}

},

我的目的是可以使用此配置运行测试。

【问题讨论】:

    标签: reactjs testing webpack jestjs


    【解决方案1】:

    我在这里找到了解决方案:https://codesandbox.io/s/github/kentcdodds/react-testing-library-examples

    当我在 package.json 中编写脚本时,它应该只是 "test": "jest" 并添加到 package.json

      "babel": {
        "presets": [
          "react-app"
        ]
      },
    

    需要用代码创建新文件 jest.config.js:

    const path = require('path')
    
    module.exports = {
      roots: [path.resolve(__dirname, './src')],
      testEnvironment: 'jest-environment-jsdom-sixteen',
      displayName: 'tests',
      testMatch: ['**//__tests__/**/*.js', '**/?(*.)+(spec|test).[jt]s?(x)'],
      testURL: 'http://localhost',
      setupFilesAfterEnv: [path.resolve(__dirname, './src/setupTests.js')],
    }
    

    我的测试文件位于 src/__ tests __/ 文件夹中,扩展名为 .test.js (i.e. app.test.js) 添加文件 setupTests.js,其中包含:

    import '@testing-library/jest-dom/extend-expect'

    之后安装jest-environment-jsdom-sixteenbabel-preset-react-app。 最后 npm test 应该可以运行并运行 __test__ 文件夹中包含的所有测试。

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2016-09-06
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 2018-12-31
      相关资源
      最近更新 更多