运行Jest测试时出现“regeneratorRuntime未定义”的错误。

98

标题已经很清楚地解释了我所面临的问题。我正在尝试测试一个具有一些状态的React组件,并尝试为该组件提供我的存储以获取它所需的内容。当我使用Jest运行组件测试时,我会收到以下错误:

ReferenceError: regeneratorRuntime is not defined

通过一些阅读,我已经确定这是由于babel-polyfillregenerator-runtime未正确应用于Jest引起的。然而,我已经尝试安装这两个包并重新运行测试,但结果没有变化。在阅读Jest Github问题页面(Remove auto-inclusion of babel-polyfill #2755)之后,我发现自2019年版本19以来,Jest不再自动包括babel-polyfill。我手动安装该软件包应该可以解决问题,但事实并非如此。我已经包含了一些我认为相关的文件。

.babelrc:

{
  "presets": ["es2015", "react", "stage-2"],
  "env": {
    "development": {
      "plugins": [
        ["react-transform", {
          "transforms": [{
            "transform": "react-transform-hmr",
            "imports": ["react"],
            "locals": ["module"]
          }]
        }]
      ]
    }
  }
}

jest.config:

{
    "transform": {
        "^.+\\.(js|jsx)$": "<rootDir>/node_modules/webpack-babel-jest",
        ".*\\.(vue)$": "<rootDir>/node_modules/jest-vue-preprocessor",
        ".*": "babel-jest"
    },
    "moduleNameMapper": {
        "\\.(jpg|jpeg|css|scss|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__tests__/__mocks__/fileMock.js",
        ".*\\.(vue)$": "vue/dist/vue.js"
    },
    "testPathIgnorePatterns": ["type_parser.spec.js", 
                               "<rootDir>/__tests__/__mocks__/",
                               "__tests__/unit/core/util/type_parser.js",
                               "__tests__/GitlabLoader.test.js"
                               ]
}

package.json

{
  "name": "my_project",
  "version": "0.2.0",
  "description": "My Project",
  "scripts": {
    "clean:build": "node ./bin/clean.js createdir",
    "build:html": "node ./bin/buildHtml.js",
    "deployProduction": "node ./bin/deployProduction.js",
    "start": "webpack-dev-server --config ./config/webpack.config.dev.js --hot --inline --progress",
    "serve": "npm run deployProduction&& supervisor --watch ./production-copy src/js/server",
    "prebuild": "npm run clean:build",
    "postbuild": "node ./bin/postBuild.js",
    "rebuild-win": "set BUILD_TYPE=preview& npm run prebuild & npm run build-win & npm run serve",
    "build": "set BUILD_TYPE=final& npm run prebuild & npm run build-win",
    "deploy": "npm run build & npm run serve",
    "build-win": "set NODE_ENV=production & npm run element-build & npm run build-doc & npm run build:html &  webpack -p --config ./config/webpack.config.prod.js --json > webpack.log.json & npm run postbuild",
    "lint": "eslint config src/js/**/*.js",
    "jscs": "jscs src/js/",
    "test": "jest --no-cache --verbose --config=./__tests__/jest.config",
    "test:watch": "npm run test -- --watch",
    "element-init": "node node_modules/element-theme/bin/element-theme -i src/js/core/ui/element-theme.css",
    "element-build": "node node_modules/element-theme/bin/element-theme -c src/js/core/ui/element-theme.css -o src/js/core/ui/element-theme ",
    "build-doc": "node bin/buildDoc.js ",
    "storybook": "start-storybook -p 9001 -c .storybook"
  },
  "repository": {
    "type": "git",
    "url": "my_url"
  },
  "license": "MIT",
  "bugs": {
    "url": "my_url"
  },
  "homepage": "my_homepage",
  "dependencies": {
    "autoprefixer": "^6.3.6",
    "axios": "^0.11.1",
    "babel-runtime": "^6.23.0",
    "babel-standalone": "^6.10.3",
    "bluebird": "^3.4.0",
    "brace": "^0.8.0",
    "browserify": "^13.0.1",
    "chai": "^3.5.0",
    "classnames": "2.2.3",
    "cls-bluebird": "^1.0.1",
    "codemirror": "^5.16.0",
    "connect-history-api-fallback": "^1.3.0",
    "continuation-local-storage": "^3.1.7",
    "dateformat": "^1.0.12",
    "diff": "^3.0.1",
    "element-theme": "^0.4.0",
    "element-ui": "^1.1.5",
    "express-history-api-fallback": "^2.0.0",
    "filedrop": "^2.0.0",
    "fs-extra": "^0.30.0",
    "history": "^2.0.2",
    "humps": "^1.0.0",
    "immutability-helper": "^2.1.1",
    "isomorphic-fetch": "^2.2.1",
    "json-loader": "^0.5.4",
    "jszip": "^3.0.0",
    "jszip-utils": "0.0.2",
    "material-ui": "^0.16.7",
    "materialize-css": "^0.97.6",
    "mocha": "^2.5.3",
    "moment": "^2.17.1",
    "normalizr": "^1.0.0",
    "raven-js": "^3.9.1",
    "react": "^15.0.1",
    "react-ace": "^3.5.0",
    "react-addons-update": "^15.4.2",
    "react-dom": "^15.0.1",
    "react-redux": "^4.4.5",
    "react-router": "^2.3.0",
    "react-router-redux": "^4.0.2",
    "redux": "^3.4.0",
    "redux-logger": "^2.6.1",
    "redux-saga": "^0.9.5",
    "request": "^2.72.0",
    "request-promise": "^3.0.0",
    "reselect": "^2.5.4",
    "save-as": "^0.1.7",
    "showdown": "^1.4.2",
    "three": "^0.79.0",
    "url-pattern": "^1.0.3",
    "vue": "^2.0.5",
    "vue-easy-slider": "^1.4.0",
    "vue-loader": "^9.8.1",
    "vue-router": "^2.0.1",
    "vue-slider-component": "^2.0.4",
    "walk": "^2.3.9"
  },
  "devDependencies": {
    "@kadira/storybook": "^2.35.3",
    "babel-core": "^6.7.6",
    "babel-eslint": "^6.1.0",
    "babel-jest": "^18.0.0",
    "babel-loader": "^6.0.2",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-polyfill": "^6.23.0",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-es2016": "^6.22.0",
    "babel-preset-react": "^6.23.0",
    "babel-preset-stage-2": "^6.5.0",
    "babel-register": "^6.7.2",
    "chai": "3.5.0",
    "chai-jquery": "2.0.0",
    "cheerio": "0.20.0",
    "colors": "1.1.2",
    "concurrently": "^2.0.0",
    "copy-webpack-plugin": "2.1.1",
    "css-loader": "0.23.1",
    "element-theme-default": "^1.1.5",
    "enzyme": "^2.7.1",
    "eslint": "^2.13.1",
    "eslint-config-airbnb": "^9.0.1",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^5.2.2",
    "express": "^4.13.4",
    "extract-text-webpack-plugin": "1.0.1",
    "file-loader": "0.8.5",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^19.0.2",
    "jest-cli": "^18.1.0",
    "jest-css-modules": "^1.1.0",
    "jest-enzyme": "^2.1.2",
    "jest-vue-preprocessor": "^0.1.2",
    "jquery": "2.2.3",
    "jscs": "3.0.3",
    "jsdoc-to-markdown": "^2.0.0",
    "jsdom": "8.4.0",
    "json-loader": "^0.5.4",
    "mocha": "^2.4.5",
    "ncp": "^2.0.0",
    "node-sass": "3.7.0",
    "postcss-loader": "0.8.2",
    "react-addons-test-utils": "^15.4.2",
    "react-hot-loader": "1.3.0",
    "react-test-renderer": "^15.4.2",
    "react-transform-hmr": "^1.0.4",
    "redux-devtools": "^3.3.1",
    "redux-devtools-dock-monitor": "^1.1.1",
    "redux-devtools-log-monitor": "^1.0.11",
    "regenerator-runtime": "^0.10.3",
    "remotedev": "^0.1.2",
    "rimraf": "^2.5.2",
    "sass-loader": "3.2.0",
    "storybook-addon-material-ui": "^0.7.6",
    "style-loader": "0.13.1",
    "url-loader": "0.5.7",
    "vueify": "^9.4.0",
    "webpack": "^1.13.0",
    "webpack-babel-jest": "^1.0.4",
    "webpack-dev-middleware": "^1.6.1",
    "webpack-dev-server": "^1.16.3",
    "webpack-hot-middleware": "^2.10.0"
  }
}

"我手动安装了那个软件包,本应该解决问题,但实际上没有。" 你在任何地方导入这个软件包吗?仅仅安装它是没有用的。 - Felix Kling
1
我尝试在我的测试文件中执行 import "babel-polyfill",并在我的 .babelrcplugins 部分提供它,但没有任何变化。 - rafafan2010
11个回答

128

如果您正在使用 setupTests.js 文件,您可以从那里导入 regenerator-runtime

// setupTests.js

import 'regenerator-runtime/runtime'
import Enzyme from 'enzyme'
import EnzymeAdapter from 'enzyme-adapter-react-16'

Enzyme.configure({
  adapter: new EnzymeAdapter()
})

然后您可以在每个测试文件中导入setupTests.js,或者更好地,在您的package.json中仅向jest配置添加setupFilesAfterEnv:

// package.json

{
  ...
  "dependencies": {
    ...
  },
  "devDependencies": {
    ...
  },
  "jest": {
    "setupFilesAfterEnv": ["./pathToYour/setupTests.js"] 
  }
}

不要忘记安装regenerator-runtime包:

$ yarn add regenerator-runtime --dev

 
没有必要导入完整的babel-polyfill(或@babel/polyfill,如果Babel ≥ v.7.0.0)。顺便提一下,它已经被弃用了,建议直接包含core-js/stable和regenerator-runtime/runtime。


2
是的@Periback,如果您只是用regenerator-runtime进行测试,那么应将其包含为dev依赖。 $ yarn add regenerator-runtime --dev - Jero
3
@rafafan2010,你能否接受这个答案?它是2020年更好的答案。不涉及添加其他依赖项。自 node 10 起就得到支持,因此不需要使用 Babel。 - Jansky
4
"将 import 'regenerator-runtime/runtime' 添加进来就可以了!谢谢!!" - Josh Yolles
5
如果您还没有使用 setupTests.js 文件,将其添加到 jest.config 文件可能更简单:setupFilesAfterEnv: [ require.resolve('regenerator-runtime/runtime') ], 意思是在 jest.config 文件中添加以上代码,以便在测试之前自动加载 regenerator-runtime/runtime 模块。 - Michael Keenan
4
@MichaelKeenan,上述解决方案setupFilesAfterEnv: [require.resolve('regenerator-runtime/runtime')]对我的情况奏效了。谢谢! - Rex Osariemen
显示剩余4条评论

65

babel-polyfill导入到每个测试中可以工作,但是更新的jest文档(v24)建议在您的babel配置中设置此项。如果您这样做,您将不再需要导入babel-polyfill。(就我而言,我错过了从我的配置中缺少的targets选项。)

// babel.config.js
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
};

一句话提醒:指定targets会覆盖您定义的任何browserslist配置(否则Babel将使用该配置)。因此,在Web项目中,您可能需要创建一个动态的babel.config.js,它是“jest-aware”的,这样只有在测试环境下才会添加targets。请参阅Jest文档中标题为“使您的Babel配置具备jest感知能力”的部分。


3
这并没有解决我的问题:只有安装 @babel/plugin-transform-runtime 并将其配置为插件,使用 "plugins": ["@babel/plugin-transform-runtime"]" 才解决了这个问题。 - Giorgio Tempesta
1
已接受的答案虽然可行,但很糟糕。问题的关键是,正如这个答案所指出的那样,正确的 babel.config.js 配置。 - Adam Jenkins

45

我使用了import "babel-polyfill"并解决了我的问题。

更新于2020年: 此答案已过时,babel-polyfill已被弃用。请查看文档Jero的答案


7
你是从哪个文件导入的? - Patrick Szalapski
1
我将其导入到我的实际测试中,问题得到了解决。 - Caleb Swank
1
为什么在 webpack 配置文件的 entry 中全局添加它没有解决问题?每个测试都导入它也不是理想的解决方案。 - vsync
9
babel-polyfill已经被弃用,请勿使用。点击此处查看发生了什么以及原因:https://babeljs.io/blog/2019/03/19/7.4.0#core-js-3-7646-https-githubcom-babel-babel-pull-7646。请遵循@jero的解决方案。 - Luc Kim-Hall
安装 @babel/plugin-transform-runtime @babel/runtime 并将 @babel/plugin-transform-runtime 添加为您的 babel.config.js 插件。请参见此处:https://dev59.com/rlUL5IYBdhLWcg3wDkdT - ntilwalli
显示剩余2条评论

29

使用安装了babel-core@bridge@babel/core@7:

我通过添加插件@babel/plugin-transform-runtime并将以下内容传递给我的babel配置来解决了这个问题:

{
 // ...
 env: {
   test: {
     // ...
      plugins: [
        '@babel/plugin-transform-runtime'
      ]
    }
  }
}

编辑或者,正如其他人评论的,您也可以将一个选项添加到@babel/preset-env的配置中,它应该就能正常工作:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}


4
这解决了我的问题,也不需要添加 regenerator: true 选项。设置 "plugins": ["@babel/plugin-transform-runtime"] 就足够了。 - Giorgio Tempesta
1
这对我也有效,而且没有添加 regenerator: true 选项。 - user616
1
这也解决了我的问题,我之前正在使用 '@bable/plugin-transform-modules-commonjs',但它效果不是很好。 - Punter Bad
备选答案对我有用。将 targets 添加到 @babel/preset-env - coderpc
1
第二个答案也可以在jest文档中找到,它讲述了如何与babel一起使用。 - xunux

20

如果您在2020年遇到此问题,经过深入浏览SO后,以下是我从其他答案中缺失的信息。

我的项目按建议配置在Babel 7.9.0设置中。在遵循所有这些步骤并将'@babel/register'导入到我的两个入口点的顶部后,引用错误仍然存在。从jest文档中,我发现了解决我的问题的方法:

// babel.config.js

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

Jest文档参考


非常感谢,这在2021年帮了很大的忙!使用 babel 7.13 - Ilya Kushlianski
我同意这很可能是2020年后遇到此问题的人们最好的答案。 - Jeremy Murray
虽然这个答案可能对某些人有用,但它没有解决我的问题;我需要的是 import 'regenerator-runtime/runtime' - rinogo

20

截至2019年10月2日的最新解决方案是在您的setupTests.js文件中导入以下内容。

import 'core-js/stable';
import 'regenerator-runtime/runtime';

babel-polyfill已经过时。


我们在Jest中需要核心JS吗? - gaurav5430
非常有帮助,让我想了好几个小时。 - Agniveer

4

如果有人在搜索错误信息时来到这里,但没有使用Babel,则可能是项目目录中存在旧的Babel配置文件,因为根据Jest文档

Making your Babel config jest-aware
[...]
Jest will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the transform configuration option:

// jest.config.js
module.exports = {
  transform: {},
};

3

继续Jero的回答,如果你在使用npm,可以执行 npm i -D regenerator-runtime 之后,在你的测试文件中执行 import 'regenerator-runtime/runtime';


3

我正在使用Vuejs、Vue Jest和Laravel Mix,这对我很有效。

import 'regenerator-runtime/runtime'
import { mount } from '@vue/test-utils'
import App from '../App';

// eslint-disable-next-line no-undef
test('it works', () => {
  // eslint-disable-next-line no-undef
  expect(1 + 1).toBe(2);
});

// eslint-disable-next-line no-undef
test('should mount without crashing', () => {
  const wrapper = mount(App);
  // eslint-disable-next-line no-undef
  expect(wrapper).toMatchSnapshot();
});


1

我在使用NodeJS的Supertest测试我的端点时遇到了问题:

问题是:

"测试套件无法运行

ReferenceError: regeneratorRuntime未定义"

解决方法如下:

  1. 我安装了:

    npm install --save-dev @babel/plugin-transform-runtime

然后在.babelrc中(除其他选项外):

我添加了

{
  "env": {
    "test": {
      "plugins": ["@babel/plugin-transform-runtime"]
    }
  }
}

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