添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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. Details: /home/xueyou/workspace/projects/node_modules/lodash-es/lodash.js:10 import * as lodash from 'lodash-es' SyntaxError: Unexpected token *

查阅 issues 发现, 目前 jest 不支持 em 模块, 只有通过 babel 去处理了

yarn add --dev babel-jest @babel/core @babel/preset-env babel-plugin-transform-es2015-modules-commonjs

配置 babel.config.js

module.exports = {
    presets: [
            "@babel/preset-env",
                targets: {
                    node: "current"
    plugins: ["transform-es2015-modules-commonjs"]
module.exports = {
    preset: "ts-jest",
    testMatch: ["<rootDir>/tests/**/*.(spec|test).ts?(x)"],
    transform: {
        // 将.js后缀的文件使用babel-jest处理
        "^.+\\.js$": "babel-jest",
        "^.+\\.(ts|tsx)$": "ts-jest"
    // 下面非要从重要, 将不忽略 lodash-es, other-es-lib 这些es库, 从而使babel-jest去处理它们
    transformIgnorePatterns: ["<rootDir>/node_modules/(?!(lodash-es|other-es-lib))"]
  • Unexpected import inside nodejs module
  • Unexpected Token Import for ES6 modules
  •