Jest неожиданный идентификатор требуется - PullRequest
1 голос
/ 26 апреля 2019

Я пытаюсь настроить Jest для тестирования моего приложения по мере его роста. Я получаю сообщение об ошибке ниже:

SyntaxError: Unexpected identifier

> 1 | const screenSize = require("../src/index.js").screenSize;
    |                    ^

Я использую Phaser 3 , Webpack , Babel и React . Я относительно новичок во всем, кроме React.

Я следовал учебному пособию Jest для начинающих и использовал с учебником веб-пакета , но я все еще получаю сообщение об ошибке.

package.json

{
  "name": "phaser3-project-template",
  "version": "1.1.0",
  "description": "A Phaser 3 Project Template",
  "main": "src/index.js",
  "scripts": {
    "build": "webpack --config webpack/prod.js ",
    "start": "webpack-dev-server --config webpack/base.js --open",
    "test": "jest"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/photonstorm/phaser3-project-template.git"
  },
  "author": "Richard Davey <rdavey@gmail.com> (http://www.photonstorm.com)",
  "license": "MIT",
  "licenseUrl": "http://www.opensource.org/licenses/mit-license.php",
  "bugs": {
    "url": "https://github.com/photonstorm/phaser3-project-template/issues"
  },
  "homepage": "https://github.com/photonstorm/phaser3-project-template#readme",
  "devDependencies": {
    "@babel/core": "^7.4.3",
    "@babel/plugin-proposal-class-properties": "^7.4.0",
    "@babel/preset-env": "^7.4.3",
    "@babel/preset-react": "^7.0.0",
    "babel-jest": "^24.7.1",
    "babel-loader": "^8.0.5",
    "clean-webpack-plugin": "^1.0.0",
    "file-loader": "^3.0.1",
    "html-webpack-plugin": "^3.2.0",
    "jest": "^24.7.1",
    "path": "^0.12.7",
    "raw-loader": "^1.0.0",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "terser-webpack-plugin": "^1.2.1",
    "webpack": "^4.28.3",
    "webpack-cli": "^3.2.1",
    "webpack-dev-server": "^3.1.14",
    "webpack-merge": "^4.2.1"
  },
  "dependencies": {
    "babel-core": "^6.26.3",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^2.1.1",
    "phaser": "^3.16.2",
    "react-redux": "^7.0.2",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    "style-loader": "^0.23.1"
  },
  "jest": {
    "modulePaths": [
      "node_modules"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ],
    "moduleNameMapper": {
      "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
      "\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
    }
  }
}

WebPack / base.js

const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");

module.exports = {
  mode: "development",
  devtool: "eval-source-map",
  entry: "./src/index.js", //do we need this?
  output: {
    path: path.resolve("dist"),
    filename: "index_bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [{ loader: "style-loader" }, { loader: "css-loader" }]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: "babel-loader"
      },
      {
        test: [/\.vert$/, /\.frag$/],
        use: "raw-loader"
      },
      {
        test: /\.(gif|png|jpe?g|svg|xml)$/i,
        use: "file-loader"
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(["dist"], {
      root: path.resolve(__dirname, "../")
    }),
    new webpack.DefinePlugin({
      CANVAS_RENDERER: JSON.stringify(true),
      WEBGL_RENDERER: JSON.stringify(true)
    }),
    new HtmlWebpackPlugin({
      template: "./index.html",
      filename: "index.html",
      inject: "body"
    })
  ]
};

.babelrc.js

const presets = [
  [
    "@babel/env",
    {
      targets: {
        browsers: [">0.25%", "not ie 11", "not op_mini all"],
        node: "current"
      },
      modules: false
    }
  ],
  "@babel/preset-react"
];
const plugins = ["@babel/plugin-proposal-class-properties"];

module.exports = { presets, plugins };

jest.config.js

"use strict";

module.exports = {
    testMatch: ["<rootDir>/**/*.test.js"],
    testPathIgnorePatterns: ["/src/", "node_modules"]
};

index.test.js

const screenSize = require("../src/index.js").screenSize;
//import toBeType from "jest-tobetype";

console.log(screenSize);

test("screenSize is an object", () => {
  expect(typeof screenSize).toBe("object");
});

Github Repo

Как мне заставить Jest обработать синтаксис es6?

1 Ответ

0 голосов
/ 09 июля 2019

Require - это синтаксис среды узла для импорта переменных, и Jest запускается в узле. В этом SO вопросе

можно найти дополнительную информацию о различиях между import / require и node.

Вы можете добавить поддержку для этого с

npm install --save-dev @babel/plugin-proposal-class-properties @babel/plugin-transform-modules-commonjs

и включите их в качестве пресетов в ваш babelrc.js

const presets = [
  [
    "@babel/env",
    {
      targets: {
        browsers: [">0.25%", "not ie 11", "not op_mini all"]
      },
      modules: false
    }
  ],
  "@babel/preset-react"
];
const plugins = [
  "@babel/plugin-proposal-class-properties",
  "@babel/plugin-transform-modules-commonjs"
];
module.exports = { presets, plugins };

В приведенном выше коде все еще будут встречаться сведения об ошибках, которые можно найти здесь: https://medium.com/@Tnodes/setting-up-jest-with-react-and-phaser-422b174ec87e

...