【问题标题】:Jest encountered an unexpected token because trying to import a file which Jest cannot parseJest 遇到了意外的令牌,因为尝试导入 Jest 无法解析的文件
【发布时间】:2019-12-09 18:28:23
【问题描述】:

PS E:\react\Code\UI> 纱线测试 纱线运行 v1.17.3 $开玩笑 失败源/App.test.js ● 测试套件无法运行

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.

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

Details:

E:\react\Code\UI\src\mainpage.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){body{font-size:12px;font-family:arial,sans-serif;background-size:200% 100%!important;height:100vh}
                                                                                             ^

SyntaxError: Unexpected token {

  1 | import React, { Component } from "react";
> 2 | import "../mainpage.css";
    | ^
  3 | import { connect } from "react-redux";
  4 | import propTypes from "prop-types";
  5 | import { fetchPost } from "../redux/action/postaction";

  at ScriptTransformer._transformAndBuildScript (E:\react../../../../Code/UI/node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
  at ScriptTransformer.transform (E:\react../../../../Code/UI/node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
  at Object.<anonymous> (E:\react../../../../Code/UI/src/page/Header.js:2:1)

测试套件:1 个失败,总共 1 个 测试:共 0 快照:共 0 个 时间:3.592s 运行所有测试套件。 错误命令失败,退出代码为 1。 info 请访问https://yarnpkg.com/en/docs/cli/run 获取有关此命令的文档。

【问题讨论】:

    标签: reactjs testing react-redux jestjs enzyme


    【解决方案1】:

    模拟你的 css 文件

    Jest 不知道如何处理 css 文件。您需要在开玩笑的配置中处理它们。有很好的信息here

    但本质上你需要在你的 jest 配置中添加这样的东西

    // package.json (for CSS Modules)
    {
      "jest": {
        "moduleNameMapper": {
          "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
          "\\.(css|less)$": "identity-obj-proxy"
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多