Jest 遇到了一个意外的标记。

54
不确定为什么它在这一行抱怨:
const wrapper = shallow();
/Users/leongaban/projects/match/bitcoin/src/components/bitcoinWidget.test.js: Unexpected token (17:26)

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:
  15 |
  16 | describe('when rendering', () => {
 >17 |   const wrapper = shallow(<BitcoinWidget {...props} />);
  18 |                           ^
  19 |   it('should render a component matching the snapshot', () => {
  20 |     const tree = toJson(wrapper);

整个测试:

import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';

// Local components
import BitcoinWidget from './bitcoinWidget';

const props = {
  logo: 'foobar',
  coin: {
    price: 0
  },
  refresh: jest.fn()
}

describe('when rendering', () => {
  const wrapper = shallow(<BitcoinWidget {...props} />);

  it('should render a component matching the snapshot', () => {
    const tree = toJson(wrapper);
    expect(tree).toMatchSnapshot();
    expect(wrapper).toHaveLength(1);
  });
});

组件

import React from 'react';

const BitcoinWidget = ({ logo, coin : { price }, refresh }) => {
  return (
    <div className="bitcoin-wrapper shadow">
      <header>
        <img src={logo} alt="Bitcoin Logo"/>
      </header>
      <div className="price">
        Coinbase
        ${price}
      </div>
      <button className="btn striped-shadow white" onClick={refresh}>
        <span>Refresh</span>
      </button>
    </div>
  );
}

export default BitcoinWidget;

还有我的 package.json 文件

{
  "name": "bitcoin",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-redux": "^5.0.7",
    "react-scripts": "1.1.5",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "eject": "react-scripts eject",
    "test": "yarn run test-jest:update --verbose --maxWorkers=2",
    "test-jest:update": "jest src --updateSnapshot",
    "test-jest": "jest src"
  },
  "now": {
    "name": "bitcoin",
    "engines": {
      "node": "8.11.3"
    },
    "alias": "leongaban.com"
  },
  "jest": {
    "verbose": true,
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/assetsTransformer.js"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ]
  },
  "devDependencies": {
    "enzyme": "^3.4.4",
    "enzyme-to-json": "^3.3.4",
    "jest": "^23.5.0"
  }
}
10个回答

15

在您的 package.json 的 jest 配置中添加此内容。

"transform": {
      "\\.js$": "<rootDir>/node_modules/babel-jest"
    },

如果问题仍然存在,请告诉我。


2
我还缺少 babel-plugin-transform-es2015-destructuring babel-plugin-transform-object-rest-spread enzyme-adapter-react-15 eslint-config-airbnb. - Leon Gaban
太好了。这通常发生在第一次配置jest时。我也遇到过同样的情况。很高兴你的问题已经解决了。 - Sakhi Mansoor
@AnupamMaurya 我在我的评论中列出了它们。 - Leon Gaban
它帮了很大的忙。太好了。 - Biplov Kumar
1
是的,这在我的情况下不起作用。 - Pintu Rajput
显示剩余2条评论

11

对于使用create-react-app的人来说,当使用create-react-app时,只有特定的jest配置可以在package.json中更改。

我遇到了Jest无法识别我的内部库的问题,Jest会在我从这个库导入的地方显示“意外的令牌”错误。

为解决此问题,您可以将测试脚本更改如下: "test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",


这对我有用,在使用外部库的类似情况下也有效。 - jckmlczk
3
我有一个 CRA TS 应用程序,在测试中遇到了 axios 的导入错误。 我更新了测试脚本为 react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\" --env=jsdom,然后它就可以工作了。谢谢! - sohammondal
1
正如@sohammondal所指出的那样,您应该使用双引号而不是单引号。 - humleflue

10

对于那些遇到这个问题,但以上任何答案都不起作用的人。

经过长时间的搜索,我采用了以下解决方案:

编辑您的jest.config.js文件以添加transformIgnorePatterns选项。

//jest.config.js

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(test).ts?(x)"],
    transform: {
        "^.+\\.(js|ts)$": "ts-jest",
    },
    transformIgnorePatterns: [
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.js$",
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.ts$",
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.tsx$",
    ],
}

将您想要忽略的包放在[]中,并使用|分隔它们。

在我的情况下是[@autofiy/autofiyable|@autofiy/property]


老实说,我不知道是什么原因导致了这个问题。 - Ali Faris
这是Jest在错误消息的第一行中建议的(参见原始问题)。 - Dmitriy

5

我在我的package.json文件中添加了jest的更新。

"jest": {
  "transformIgnorePatterns": [
    "node_modules/(?!(<package-name>|<second-package-name>)/)"
  ]
},

如果不需要,可以随意删除|<second-package-name>

您也可以像@paulosullivan22提到的那样将其作为脚本的一部分来执行。

"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<package-name>)/)'"


4

在使用Webpack创建React应用程序并设置Jest时,我遇到了相同的错误。我不得不添加@babel/preset-env,然后问题就解决了。我也写了一篇关于此问题的博客文章。

npm i -D @babel/preset-env

然后将其添加到.babelrc文件的“presets”中,例如:

{ 
  "presets": ["@babel/react", "@babel/env"]
}

https://medium.com/@shubhgupta147/how-i-solved-issues-while-setting-up-jest-and-enzyme-in-a-react-app-created-using-webpack-7e321647f080?sk=f3af93732228d60ccb24b47ef48d7062


2

我更新了一些依赖项(如react、jest等),但是出现了以下错误:

Jest遇到了一个意外的标记 - SyntaxError: Cannot use import statement outside a module

我有一些需要转码的dev依赖项。

首先,我重新开始了所有操作:

$ jest --init

现在生成了 jest.config.js 文件(之前我只在 package.json 中配置 Jest )。

在错误消息下的详细信息中,您可以看到报告模块,对我来说它看起来像这样:

Details: /<project_root>/node_modules/axios/index.js:1

在 jest.config.js 中添加以下转换忽略解决了我的问题:

transformIgnorePatterns: [
    "node_modules/(?!axios.*)"
],

现在axios模块已经成功转译,不再出现问题,希望这能帮到你!


1
以下对我来说是有效的。 创建babel.config.js文件。
module.exports = {
  presets: [
    [ '@babel/preset-env', { targets: { esmodules: true } } ],
    [ '@babel/preset-react', { runtime: 'automatic' } ],
  ],
};

1
在我的情况下,问题是我在模拟的模块中导入了原始模块:
import urlExist from "url-exist";

async function stubbedUrlExist(): Promise<boolean> {
  // do something
}

export default stubbedUrlExist;

解决方案是在url-exist模拟中不导入url-exist。这可能会导致循环导入。Jest可能会在处理模块加载的通用try<>catch块中捕获此错误。

0

使用转换器无法使其工作,最终我模拟了依赖项:

创建一个文件:<path>/react-markdown.js

import React from 'react';

function ReactMarkdown({ children }){
  return <>{children}</>;
}

export default ReactMarkdown;

在 jest.config.js 文件中添加:
module.exports = {
  moduleNameMapper: {
    'react-markdown': '<path>/mocks/react-markdown.js',
  },
};

感谢juanmartinez在https://github.com/remarkjs/react-markdown/issues/635上的贡献。


0

以下对我有效

module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-typescript", "@babel/react"
  ]
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接