首页 > 解决方案 > Jest 不能使用 ES6 导入语法和别名解析器

问题描述

我跑了node --experimental-vm-modules node_modules/.bin/jest --no-cache,得到了以下异常。我已经尝试了几个小时并搜索了所有可能的解决方案,似乎 jest/babel/webpack 是一团糟。它无法评估应该是基本且通用但在 Jest 上不可用的 ES6 语法?

在我们的项目中,我们经常使用我们自己的模块@customPkg并托管在我们的 NPM 服务器中。

并且源代码在我们的代码库中随处导入@customPkg

有什么想法可以在不更改源代码的情况下让 jest 运行吗?

失败功能测试/单元/Sample.mocha.jsx

● 测试套件未能运行

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • 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/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/packages/my_app/node_modules/@customPkg/customPkg/index.js:14
export * from "@customPkg/application";
^^^^^^

SyntaxError: Unexpected token 'export'

示例.mocha.jsx

import * as React from 'react';
import { MyApp } from '../../../../src/MyApp';

我的应用

/**
 * @prettier
 */
14. import * as customPkg from '@customPkg/customPkg';

jest.config.js(customPkg 在 node_modules 中)


module.exports = {
    testEnvironment: 'jsdom',
    'transformIgnorePatterns': [
        'node_modules/?!(@customPkg)'
    ],

    moduleNameMapper: {
        '^@customPkg': '<rootDir>/node_modules/@customPkg',
    },
    moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
    modulePaths: [
        'src/',
        'node_modules/'
    ],

};

包.json


"jestTest": "NODE_OPTIONS=--experimental-vm-modules jest --config=jest.config.js ",

"jest": {
    "moduleFileExtensions": [
        "js",
        "jsx"
    ],
    "moduleDirectories": [
        "node_modules",
        "bower_components",
        "src"
    ]
},


devDependencies

        "@jest/globals": "^27.0.3",
        "@testing-library/dom": "^7.31.2",
        "@testing-library/jest-dom": "^5.14.1",
        "@types/jest": "^26.0.23",
        "babel-jest": "^27.0.2",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "global-jsdom": "^8.1.0",
        "jest": "^27.0.4",
        "jest-canvas-mock": "^2.3.1",

标签: javascriptnode.jsjestjsbabeljsbabel-jest

解决方案


推荐阅读