programing

Jest 테스트 실행 시 'regeneratorRuntime'이 정의되지 않음

mailnote 2023. 3. 17. 21:47
반응형

Jest 테스트 실행 시 'regeneratorRuntime'이 정의되지 않음

제목이 내가 직면한 상황을 거의 설명해준다.테스트하려고 합니다.React컴포넌트가 필요한 것을 얻기 위해 컴포넌트에 스토어를 제공하려고 합니다.Jest를 사용하여 컴포넌트 테스트를 실행하면 다음 오류가 나타납니다.

ReferenceError: regeneratorRuntime is not defined

어떤 독서를 통해 이 원인이babel-polyfill또는regenerator-runtimeJest에 올바르게 적용되지 않습니다.그러나 저는 두 패키지를 모두 설치해서 다시 실행해 보았습니다만, 결과는 변하지 않았습니다.Jest Github issues 페이지(Babel-polyfill #2755의 자동 포함 제거)를 읽은 후 다음과 같은 사실을 알게 되었습니다.babel-polyfill는 버전 19에서 Jest에 의해 자동으로 포함되지 않습니다.그 패키지를 수동으로 설치해도 문제가 해결되지 않았습니다.제가 관련 있다고 생각되는 파일 몇 개를 포함했습니다.

.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"
  }
}

셋업을 사용하는 경우Tests.js 파일은 여기서 재생기 런타임 Import할 수 있습니다.

// setupTests.js

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

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

 
그런 다음 설정을 가져올 수 있습니다.패키지의 모든 테스트 파일 이상에 대해 tests.js를 실행합니다.jsonsetupFilesAfterEnv를 joke 설정에 추가합니다.

// package.json

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

 
리제너레이터 런타임 패키지를 설치하는 것을 잊지 마십시오.

$ yarn add regenerator-runtime --dev

 
btw가 core-js/stable 및 regenerator-runtime/runtime을 직접 포함하기 위해 폐지된 완전한 babel-poly fill(또는 Babel † v.7.0.0의 경우 @babel/polyfill)을 가져올 필요가 없습니다.

Import 중에babel-polyfill동작하는 각 테스트에 대해 Updated jeast docs(v24)에서는 babel Configuration에서 이 설정을 권장합니다.이렇게 하면 더 이상 가져올 필요가 없습니다.babel-polyfill. (개인적으로, 저는 이 모든 것을 놓치고 있었습니다.targets내 옵션에서preset-env설정)을 클릭합니다).

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

현명한 사람들에게 하는 말:targets모든 것을 덮어씁니다.browserslist(바벨이 사용하지 않는 경우)를 설정합니다.따라서 웹 프로젝트에서는 아마도 다이내믹을 만들고 싶을 것입니다.babel.config.js'위험 인식'이기 때문에 추가만 할 수 있습니다.targets테스트 환경일 때 사용합니다.joke 문서의 "Making your Babel config joke-aware" 섹션을 참조하십시오.

나는 사용했다import "babel-polyfill"제 고민도 해결됐어요

업데이트 2020:이 답변은 구식입니다.babel-polyfill는 권장되지 않습니다.문서와 제로의 살펴보세요.

와 함께babel-core@bridge인스톨 및@babel/core@7:

플러그인을 추가하고 다음 babel config로 전달하여 문제를 해결했습니다.

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

편집: 다른 사용자의 코멘트에 따라 다음 옵션 중 하나만 추가할 수도 있습니다.@babel/preset-env

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

2020년에 이 문제를 겪고 있는 분들을 위해 SO를 꼼꼼히 읽어본 결과, 제가 다른 답변에서 누락된 정보를 찾아냈습니다.

내 프로젝트는 Babel 7.9.0 설정에서 제안된 대로 구성되어 있습니다.이 모든 단계를 수행하고 Import한 후'@babel/register'ReferenceError를 참조합니다.농담 문서를 통해 다음과 같은 문제를 해결했습니다.

// babel.config.disc

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

Jest 문서 참조

10월 2일 이후를 입니다.setupTests.jsfilename을 클릭합니다.

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

babel-polyfill을 사용하다

오류 메시지를 검색할 때 누군가가 여기에 도착했지만 Babel을 사용하지 않는 경우 Jest 문서에 따라 오래된 Babel 구성 파일이 프로젝트 디렉토리에 존재할 수 있습니다.

config Babel Configuration' joke-aware'를 합니다.
[...]
프로젝트에 babel 구성이 있는 경우 Jest는 자동으로 파일을 변환합니다.하려면 , 옵션을 명시적으로 리셋 할 수.

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

이치 npm을 사용할 수 .npm i -D regenerator-runtime 다음에 또 한 번.import 'regenerator-runtime/runtime';테스트 파일에 있습니다.

나는 라라벨 믹스에서 Vuejs, Vue Jest를 사용하고 있는데 이것은 나에게 효과가 있다.

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();
});

노드의 Supertest를 사용하여 엔드포인트를 테스트하는 동안 이 문제가 발생했습니다.JS:

문제는

"테스트 스위트 실행에 실패했습니다.

ReferenceError: regeneratorRuntime이 정의되지 않았습니다."

해결책은 다음과 같습니다.

  1. 설치 완료:

    npm install --save-dev @babel/module-module

그런 다음 .babelrc(다른 옵션 제외):

추가했습니다.

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

왜죠

공식 제스트 문서에 따르면 더 이상 자동으로 주입되지 않습니다.

Jest는 재생기 런타임에 자동으로 삽입되지 않습니다.이것에 관한 에러가 발생했을 경우는, @babel/preset-env 와 같이 비동기 함수를 적절히 변환하도록 Babel 을 설정합니다.관련 홍보

어떻게.

PR을 살펴보면 다음과 같은 솔루션을 이용할 수 있습니다.

@babel/plugin-transform-runtime

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

@babel/runtime

npm install @babel/runtime

다음 이것을 (바벨 설정babel.config.js

{
  "plugins": [
    [ "@babel/plugin-transform-runtime", { "regenerator": true } ]
  ]
}

언급URL : https://stackoverflow.com/questions/42535270/regeneratorruntime-is-not-defined-when-running-jest-test

반응형