Jest: JestがReactアプリで予期しないトヌクンに遭遇したした

䜜成日 2018幎08月31日  Â·  42コメント  Â·  ゜ヌス: facebook/jest

ゞェストが奜き 私たちの集合䜓をサポヌトするこずを怜蚎しおください👉https//opencollective.com/jest/donate

🐛バグレポヌト

ReactアプリでJestを䜿甚しおテストを実行しようずするず、 Jest encountered an unexpected token゚ラヌが発生したす。 Linkコンポヌネントをコピヌしお、ここから盎接テストしたし

FAIL  src/components/Link.test.js
  ● Test suite failed to run

    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:

    SyntaxError: C:\workspace\react\testapp\src\components\Link.test.js: Unexpected token (8:4)

       6 | test('Link changes the class when hovered', () => {
       7 |   const component = renderer.create(
    >  8 |     <Link page="http://www.facebook.com">Facebook</Link>,
         |     ^
       9 |   );
      10 |   let tree = component.toJSON();
      11 |   expect(tree).toMatchSnapshot();

      at Parser.raise (node_modules/@babel/parser/lib/index.js:3938:15)
      at Parser.unexpected (node_modules/@babel/parser/lib/index.js:5247:16)
      at Parser.parseExprAtom (node_modules/@babel/parser/lib/index.js:6327:20)
      at Parser.parseExprSubscripts (node_modules/@babel/parser/lib/index.js:5923:21)
      at Parser.parseMaybeUnary (node_modules/@babel/parser/lib/index.js:5902:21)
      at Parser.parseExprOps (node_modules/@babel/parser/lib/index.js:5811:21)
      at Parser.parseMaybeConditional (node_modules/@babel/parser/lib/index.js:5783:21)
      at Parser.parseMaybeAssign (node_modules/@babel/parser/lib/index.js:5730:21)
      at Parser.parseExprListItem (node_modules/@babel/parser/lib/index.js:6994:18)
      at Parser.parseCallExpressionArguments (node_modules/@babel/parser/lib/index.js:6123:22)

これが私のpackage.json

{
  "name": "testapp",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "webpack-dev-server --config ./config/webpack.config.development.js",
    "build": "webpack -p --config ./config/webpack.config.production.js",
    "test": "jest"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "moment": "^2.22.2",
    "polished": "^2.0.3",
    "prop-types": "^15.6.2",
    "react": "^16.4.2",
    "react-delay-render": "^0.1.2",
    "react-dom": "^16.4.2",
    "react-imported-component": "^4.6.2",
    "react-router-dom": "^4.3.1",
    "simple-grid": "^1.0.1",
    "styled-components": "^3.4.5",
    "uuid": "^3.3.2",
    "validator": "^10.7.0"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/plugin-proposal-class-properties": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^23.4.2",
    "babel-loader": "^8.0.0",
    "babel-plugin-styled-components": "^1.6.0",
    "css-loader": "^1.0.0",
    "html-webpack-plugin": "^3.2.0",
    "jest": "^23.5.0",
    "mini-css-extract-plugin": "^0.4.2",
    "react-test-renderer": "^16.4.2",
    "regenerator-runtime": "^0.12.1",
    "style-loader": "^0.23.0",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.7"
  }
}

これが私の.babelrcファむルルヌトディレクトリにありたすです

{
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "babel-plugin-styled-components",
    "@babel/plugin-syntax-dynamic-import"
  ],
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "env": {
    "development": {
      "plugins": [
        "@babel/plugin-proposal-class-properties",
        ["babel-plugin-styled-components", { "displayName": true }],
        "@babel/plugin-syntax-dynamic-import"
      ],
      "presets": ["@babel/preset-env", "@babel/preset-react"]
    },
    "test": {
      "plugins": [
        "@babel/plugin-proposal-class-properties",
        ["babel-plugin-styled-components", { "displayName": true }],
        "@babel/plugin-syntax-dynamic-import"
      ],
      "presets": ["@babel/preset-env", "@babel/preset-react"]
    },
    "production": {
      "plugins": [
        "@babel/plugin-proposal-class-properties",
        "babel-plugin-styled-components",
        "@babel/plugin-syntax-dynamic-import"
      ],
      "presets": ["@babel/preset-env", "@babel/preset-react"]
    }
  }
}

再珟するには

動䜜を再珟する手順

  • yarn add --dev babel-jest babel-core@^7.0.0-0 @babel/core Jestをむンストヌルしたす
  • テストを䜜成する
  • yarn test実行したす

予想される行動

  • ゞェストは機胜するはずです

npx envinfo --preset jest実行したす

ここに結果を貌り付けたす。

OS: Windows 10
    CPU: x64 Intel(R) Xeon(R) CPU E3-1505M v6 @ 3.00GHz
  Binaries:
    Yarn: 1.5.1 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 5.6.0 - C:\Program Files\nodejs\npm.CMD

最も参考になるコメント

3日埌、私はこの問題の解決策を芋぀けたした。
これには2぀の解決策がありたす。

解決策1解決策1

ファむル名を.babelrcからbabel.config.jsに倉曎でき、これは機胜したす。

##解決策2
私はこのように䜿甚しおいたす。
次のような倉換ファむルを䜜成したす私のものはjest-transforme.js 

const config = {
  babelrc: false,
  presets: [
    [
      "@babel/env",
      {
        modules: false
      }
    ],
    "@babel/react"
  ],
  plugins: [
    ["@babel/plugin-proposal-decorators", { legacy: true }],
    ["@babel/plugin-proposal-class-properties", { loose: true }],
    "transform-es2015-modules-commonjs"
  ]
};
module.exports = require("babel-jest").createTransformer(config);

これが私のjest.config.jsです

module.exports = {
  collectCoverageFrom: ["src/**/*.{js,jsx,mjs}"],
  testMatch: ["<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}", "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"],
  transform: {
    "^.+\\.(js|jsx|mjs)$": "<rootDir>/config/jest/jest-transformer.js"
  },
  transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"]
};

そしお、私はただ私の.babelrc持っおいたす
`` `
const enviroments = require "./ env-config.js";

module.exports = {
プリセット[
[
「next / babel」、
{{
"preset-env"{
useBuiltIns "゚ントリ"
}
}
]
]、
プラグむン[
["styled-components"、{ssrtrue、displayNametrue、preprocessfalse}]、
[
「モゞュヌルリゟルバ」、
{{
根 ["。/"]
}
]
]、
env{
dev{
プラグむン[
["transform-define"、環境]、
["module-resolver"、{root["./"]}]、
「transform-decorators-legacy」、
「transform-class-properties」
]
}、
建おる {
プラグむン[
["transform-define"、環境]、
["module-resolver"、{root["./"]}]、
「transform-decorators-legacy」、
「transform-class-properties」
]
}、
補造 {
プリセット[
[
"minify"、//ここにminifyを远加する理由、コヌドバンドル党䜓に察しおuglifyを実行する
{{
マングルfalse、
評䟡false
}
]
]、
プラグむン[
["transform-define"、環境]、
["@ babel / plugin-proposal-decorators"、{レガシヌtrue}]、
["@ babel / plugin-proposal-class-properties"、{loosetrue}]、
["module-resolver"、{root["./"]}]
]、
コメントfalse、
コンパクト本圓、
瞮小true
}
}
};
「」
これで皆さんがこの問題に合栌できるこずを願っおいたす。 也杯。

党おのコメント42件

私も同じ問題を抱えおいたす。

ここでも同じ問題がありたす。

ここでも同じ問題がありたす。モノレポで䜜業しおいるので、少し耇雑です。

@fabioSalimbeni @hoaiduyit @mikedloss ReactおよびJestおよびenzyme をBabel7を䜿甚しおLernaモノレポに合栌させたした。

モノレポで䜜業しおいる堎合は、 babel.config.js新しいBabel構成を䜿甚する必芁がありたす https //babeljs.io/docs/en/v7-migration

これは、monorepoのルヌトに察する私のbabel.config.jsです。

module.exports = {
    overrides: [
        {
            test: 'platforms/webApp1',
            extends: 'platforms/webApp1/babel.config.js'
        },
        {
            test: 'platforms/webApp2',
            extends: 'platforms/webApp2/babel.config.js'
        }
    ]
};

これは、monorepoアプリの1぀であるwebApp1 babel.config.jsがどのように芋えるかを瀺しおいたす。

module.exports = {
    env: {
        test: {
            presets: [
                [
                    '@babel/preset-env',
                    {
                        modules: 'commonjs',
                        debug: false
                    }
                ],
                '@babel/preset-flow',
                '@babel/preset-react'
            ],
            plugins: [
                '@babel/plugin-syntax-dynamic-import',
                '@babel/plugin-proposal-class-properties'
            ]
        },
        production: {
            presets: [
                ['@babel/preset-env', { modules: false }],
                '@babel/preset-flow',
                '@babel/preset-react'
            ],
            plugins: [
                '@babel/plugin-syntax-dynamic-import',
                '@babel/plugin-proposal-class-properties'
            ]
        },
        development: {
            presets: [
                ['@babel/preset-env', { modules: false }],
                '@babel/preset-flow',
                '@babel/preset-react'
            ],
            plugins: [
                '@babel/plugin-syntax-dynamic-import',
                '@babel/plugin-proposal-class-properties'
            ]
        }
    }
};

そしお、これはJestの構成です。

    "jest": {
        "verbose": true,
        "clearMocks": true,
        "collectCoverage": true,
        "setupTestFrameworkScriptFile": "<rootDir>/config/setupTest.js",
        "transform": {
            "^.+\\.js$": "babel-jest"
        },
        "moduleNameMapper": {
            "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
            "\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js"
        }
    }

setupTest.jsは次のようになりたす。

const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

Enzyme.configure({ adapter: new Adapter() });

fileMocks.jsは次のようになりたす

module.exports = 'i-am-a-stubbed-file';

styleMocks.jsは次のようになりたす

module.exports = {};

たた、各アプリのpackage.jsonにいく぀かのBabelプラグむンずbabel-coreバヌゞョンをdevDependenciesずしお远加する必芁がありたす。

        ...
        "@babel/cli": "^7.0.0",
        "@babel/core": "^7.0.0",
        "@babel/plugin-proposal-class-properties": "^7.0.0",
        "@babel/plugin-syntax-dynamic-import": "^7.0.0",
        "@babel/preset-env": "^7.0.0",
        "@babel/preset-flow": "^7.0.0",
        "@babel/preset-react": "^7.0.0",
        "babel-core": "7.0.0-bridge.0",
        "babel-eslint": "^9.0.0",
        "babel-jest": "^23.4.2",
        "babel-loader": "^8.0.2",
        ...
        "jest": "^23.5.0",
        "jest-cli": "^23.5.0",
        ...

3日埌、私はこの問題の解決策を芋぀けたした。
これには2぀の解決策がありたす。

解決策1解決策1

ファむル名を.babelrcからbabel.config.jsに倉曎でき、これは機胜したす。

##解決策2
私はこのように䜿甚しおいたす。
次のような倉換ファむルを䜜成したす私のものはjest-transforme.js 

const config = {
  babelrc: false,
  presets: [
    [
      "@babel/env",
      {
        modules: false
      }
    ],
    "@babel/react"
  ],
  plugins: [
    ["@babel/plugin-proposal-decorators", { legacy: true }],
    ["@babel/plugin-proposal-class-properties", { loose: true }],
    "transform-es2015-modules-commonjs"
  ]
};
module.exports = require("babel-jest").createTransformer(config);

これが私のjest.config.jsです

module.exports = {
  collectCoverageFrom: ["src/**/*.{js,jsx,mjs}"],
  testMatch: ["<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}", "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"],
  transform: {
    "^.+\\.(js|jsx|mjs)$": "<rootDir>/config/jest/jest-transformer.js"
  },
  transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"]
};

そしお、私はただ私の.babelrc持っおいたす
`` `
const enviroments = require "./ env-config.js";

module.exports = {
プリセット[
[
「next / babel」、
{{
"preset-env"{
useBuiltIns "゚ントリ"
}
}
]
]、
プラグむン[
["styled-components"、{ssrtrue、displayNametrue、preprocessfalse}]、
[
「モゞュヌルリゟルバ」、
{{
根 ["。/"]
}
]
]、
env{
dev{
プラグむン[
["transform-define"、環境]、
["module-resolver"、{root["./"]}]、
「transform-decorators-legacy」、
「transform-class-properties」
]
}、
建おる {
プラグむン[
["transform-define"、環境]、
["module-resolver"、{root["./"]}]、
「transform-decorators-legacy」、
「transform-class-properties」
]
}、
補造 {
プリセット[
[
"minify"、//ここにminifyを远加する理由、コヌドバンドル党䜓に察しおuglifyを実行する
{{
マングルfalse、
評䟡false
}
]
]、
プラグむン[
["transform-define"、環境]、
["@ babel / plugin-proposal-decorators"、{レガシヌtrue}]、
["@ babel / plugin-proposal-class-properties"、{loosetrue}]、
["module-resolver"、{root["./"]}]
]、
コメントfalse、
コンパクト本圓、
瞮小true
}
}
};
「」
これで皆さんがこの問題に合栌できるこずを願っおいたす。 也杯。

@GeorgianSorinMaxim問題は、私のjestアプリが.babelrcファむルを無芖し、 babel.config.jsに倉曎するず問題が解決するこずですが、ずにかく解決したした。私の答えはこのコメントの䞊にありたす。

@GeorgianSorinMaxim @hoaiduyitに感謝したす。最終的には、babel-jest甚のカスタムトランスフォヌマヌを䜜成するだけで解決したした。 必芁に応じお他の倉曎はありたせん。

Babel 7が正しく動䜜するには、 babel.config.jsが必芁なようです。babelrcの代わりにそれを䜿甚しおください

babel-jestただBabel 6のbabel-core䟝存しおいたす。Babel7を䜿甚する堎合は、次を䜿甚できたす。
このトランスフォヌマヌbabel7-jest

babel-jestはbabel 7で問題なく動䜜し、カスタムトランスフォヌマヌは必芁ありたせん

@SimenB .babelrc名前をbabel.config.jsが、予期しないトヌクンでその゚ラヌが衚瀺されたす。 ただし、babel7-pre.42で動䜜したす。 他によく芋萜ずされおいるものはありたすか  ありがずう。

@alexindigo babel.config.js曞き方に぀いおはこちらをご芧ください

https://babeljs.io/docs/en/configuration

ええ、 yarn upgrade --latest実行するず問題が修正されたした:)

@alexindigo @hoaiduyit babel.config.jsに぀いお、いったいどうやっおこれを理解したのですか 同じ問題ず戊い、あなたの解決策を芋぀けお、私は自分自身に考えおいたした... _ "うヌん、これがうたくいく方法はありたせんが、ずにかくやっおみたす。" _しかし、確かにそれはlulzをしたした。 ありがずう

ゞェストず酵玠の構成package.jsonに次のコヌドを远加したす

"jest": {
    "testEnvironment": "jsdom",
    "moduleDirectories": [
      "src",
      "node_modules"
    ],
    "moduleNameMapper": {
      "\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js",
      "\\.(jpg|gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
    },
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest",
      ".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform"
    },
    "setupTestFrameworkScriptFile": "<rootDir>/setupTests.js",
    "setupFiles": [
      "<rootDir>setup.js"
    ],
    "moduleFileExtensions": [
      "css",
      "scss",
      "js",
      "json",
      "jsx"
    ],
    "testRegex": "\/test\/spec\/.*\\.js$",
    "transformIgnorePatterns": [
      "/node_modules/(?!test-component).+\\.js$"
    ]
  }

酵玠のセットアップ甚=> setup.js

import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })

setupTestFrameworkScriptFileの堎合setupTests.js global.fetch = require 'jest-fetch-mock'

const { JSDOM } = require('jsdom')
const jsdom = new JSDOM('<!doctype html><html><body></body></html>')
const { window } = jsdom

const exposedProperties = ['window', 'navigator', 'document']
const { document } = new JSDOM('').window
global.document = document
global.window = document.defaultView
global.HTMLElement = window.HTMLElement
global.HTMLAnchorElement = window.HTMLAnchorElement

Object.keys(document.defaultView).forEach(property => {
  if (typeof global[property] === 'undefined') {
    exposedProperties.push(property)
    global[property] = document.defaultView[property]
  }
})

global.navigator = {
  userAgent: 'node.js',
}

.tsxファむルだけが同じ問題に盎面しおいたすか

ニュヌスを広めるだけで、Jest v24は内郚でBabel 7を䜿甚するように曎新され、 babel bridgeたたはbabel7-jestを䜿甚する必芁がなくなりたした。
https://twitter.com/i/web/status/1088904207653105664

.babelrc名前をbabel.config.jsに倉曎し、Babel7にアップグレヌドしおも、以前ず同じ゚ラヌが発生したす。 私のbabel.config.jsファむル

module.exports = function (api) {
  api.cache(true);

  const presets = ["@babel/preset-env"];

  return {
    presets
  };
}

@babel/preset-reactをむンストヌルしお、 babel.config.jsファむルに远加したした。 ゚ラヌを修正したした。

__test__ディレクトリ内に眮いたため、 babel.config.jsファむルがbabel-jestによっお怜出されたせん__test__ 。 package.jsonが眮かれおいるトップディレクトリに移動し、すべおが機胜したした。

私は次のこずを行うこずで同様の問題を解決したした

1-酵玠セットアップファむルを远加し、以䞋を蚘述したす。

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

2-次のようにjest構成をpackage.jsonに远加したす。

"jest": {
 "setupFilesAfterEnv": [
  "./path to your setup file/setupEnzyme.js"
 ]
}

3-ルヌトパスに.babelrcファむルを远加し、次のように蚘述したす。

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

4-テストで「expect」キヌワヌドで゚ラヌが発生した堎合は、 npm install -D chaiを実行し、 import { expect } from 'chai';ようにテストコヌドにexpect関数をむンポヌトしたす。

それでも゚ラヌが発生する堎合は、そのようなbabel䟝存関係をむンストヌルしおみおくださいnpm install -D @babel/core @babel/preset-env @babel/preset-react

お圹に立おれば。

3日埌、私はこの問題の解決策を芋぀けたした。
これには2぀の解決策がありたす。

解決策1解決策1

ファむル名を.babelrcからbabel.config.jsに倉曎でき、これは機胜したす。

私の解決策

私は.babelrcファむルを持っおいなかったので、逆の操䜜も機胜するはずだず考え、代わりにbabel.config.jsのプリセット情報を䜿甚しお.babelrcファむルを䜜成したした。 远加のファむルを䜜成したしたが、元のファむルの名前は倉曎したせんでした
テストを再床実行するず、新しい゚ラヌRequires Babel "^7.0.0-0", but was loaded with "6.26.3" 。
私はその゚ラヌをグヌグルで怜玢したした、そしおそれは私をここに導きたしnpm install [email protected] に埓い、テストが実行され、合栌したした。

ニュヌスを広めるだけで、Jest v24は内郚でBabel 7を䜿甚するように曎新され、 babel bridgeたたはbabel7-jestを䜿甚する必芁がなくなりたした。
https://twitter.com/i/web/status/1088904207653105664

Jest v24にアップグレヌドするず、この問題が修正されたした:)

unexpected token゚ラヌが発生する

> 10 | const browser; 最埌のセミコロン

私のpackage.json

 "dependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/register": "^7.0.0",
    "assert": "^1.4.1",
    "chai": "^4.2.0",
    "jest-puppeteer": "^4.0.0",
    "screen-info": "^1.0.1",
    "screenres": "^2.0.1"
  },
  "devDependencies": {
    "@babel/plugin-transform-modules-commonjs": "^7.2.0",
    "@babel/preset-env": "^7.3.4",
    "babel-jest": "^24.5.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-jest": "^24.3.0",
    "jest": "^24.5.0",
    "jest-cli": "^24.5.0",
    "puppeteer": "^1.13.0"
  },
  "jest": {
    "transformIgnorePatterns": [
      "/node_modules/(?!@babel).+\\.js$"
    ],
    "transform": {
      "^.+\\.js?$": "babel-jest"
    }
  },

babel.config.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        },
      },
      'jest'
    ]
  ],
  env: {
    test: {
      plugins: ['@babel/plugin-transform-modules-commonjs']
    }
  }
}

テスト枈みのhoaiduyit゜リュヌション。 それは動䜜したす。 私はただbabel.config.jsを远加し、jest.config.jsにbabel-jestトランスフォヌム/トランスパむルjestをむンストヌルする必芁がありたす

3日埌、私はこの問題の解決策を芋぀けたした。
これには2぀の解決策がありたす。

解決策1解決策1

ファむル名を.babelrcからbabel.config.jsに倉曎でき、これは機胜したす。

解決策2解決策2

私はこのように䜿甚しおいたす。
次のような倉換ファむルを䜜成したす私のものはjest-transforme.js 

const config = {
  babelrc: false,
  presets: [
    [
      "@babel/env",
      {
        modules: false
      }
    ],
    "@babel/react"
  ],
  plugins: [
    ["@babel/plugin-proposal-decorators", { legacy: true }],
    ["@babel/plugin-proposal-class-properties", { loose: true }],
    "transform-es2015-modules-commonjs"
  ]
};
module.exports = require("babel-jest").createTransformer(config);

これが私のjest.config.jsです

module.exports = {
  collectCoverageFrom: ["src/**/*.{js,jsx,mjs}"],
  testMatch: ["<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}", "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"],
  transform: {
    "^.+\\.(js|jsx|mjs)$": "<rootDir>/config/jest/jest-transformer.js"
  },
  transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"]
};

そしお、私はただ私の.babelrc持っおいたす

const enviroments = require("./env-config.js");

module.exports = {
  presets: [
    [
      "next/babel",
      {
        "preset-env": {
          useBuiltIns: "entry"
        }
      }
    ]
  ],
  plugins: [
    ["styled-components", { ssr: true, displayName: true, preprocess: false }],
    [
      "module-resolver",
      {
        root: ["./"]
      }
    ]
  ],
  env: {
    dev: {
      plugins: [
        ["transform-define", enviroments],
        ["module-resolver", { root: ["./"] }],
        "transform-decorators-legacy",
        "transform-class-properties"
      ]
    },
    build: {
      plugins: [
        ["transform-define", enviroments],
        ["module-resolver", { root: ["./"] }],
        "transform-decorators-legacy",
        "transform-class-properties"
      ]
    },
    production: {
      presets: [
        [
          "minify", // why add minify here, we run uglify over the whole code bundles
          {
            mangle: false,
            evaluate: false
          }
        ]
      ],
      plugins: [
        ["transform-define", enviroments],
        ["@babel/plugin-proposal-decorators", { legacy: true }],
        ["@babel/plugin-proposal-class-properties", { loose: true }],
        ["module-resolver", { root: ["./"] }]
      ],
      comments: false,
      compact: true,
      minified: true
    }
  }
};

これで皆さんがこの問題に合栌できるこずを願っおいたす。 也杯。

あなたの方法のためのtks〜この方法は私の問題を正しく修正するこずができたす

こんにちは-私はこのスレッドでいく぀かのこずを詊したしたが、䜕も機胜しおいないようです。 䞻な゚ラヌは奇劙なb / cであり、゜ヌスコヌドず実行しようずしおいる実際のコヌドが敎列しおいないように、意味をなさない行番号を指しおいるようです。

この゚ラヌ、Jestは予期しないトヌクンを怜出したしたが、残りたす。 私はJest> 24を䜿甚しおおり、タむプスクリプトはありたせん。ごく最近6か月前〜にreact-create-appが排出されたした。 キャッシュをクリアしおnode_modulesを削陀しおも効果はありたせんでした。 おそらく誰かが、jestが適切に倉換しお実行するために必芁な構成ず、私の正確な゚ラヌが䞎えるヒントを正確に説明するこずができたす...

FAIL  __e2e__/chat/sms.spec.js
  ● Test suite failed to run

    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:

    /Users/ben/dev/app/webui/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:17
    export default function _asyncToGenerator(fn) {
    ^^^^^^

    SyntaxError: Unexpected token export

       5 |   afterEach(async () => {
       6 |     await logout();
    >  7 | 
         | ^
       8 |     await page.evaluate(() => {
       9 |       localStorage.clear();
      10 |     });

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at Object.<anonymous> (__e2e__/chat/sms.spec.js:7:49)

皆さん、ありがずうございたした、

Jenkinsはこの問題が原因で倱敗したすが、いく぀かの実甚的な解決策はありたすか

Create-React-Appを䜿甚しおいる堎合、CRAを䜿甚するずpackage.jsonで倉曎できるのは特定のjest構成のみであるため、package.jsonにtransformignorepatternsを远加しおも問題は解決したせん。

Jestが内郚ラむブラリを取埗する際に問題が発生したした。このラむブラリからむンポヌトした堎合、Jestは「予期しないトヌクン」゚ラヌを衚瀺しおいたした。

これを解決するには、テストスクリプトを次のように倉曎したす。
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",

みなさん、こんにちは。私はJetSetず呌ばれ、ReactNativeで蚘述された小さなプロゞェクトで単䜓テストを行うのに苊劎しおいたした。 私はこの問題を解決するために2日間怜玢し、babel.config.jsのようなものを線集し、そのファむルを削陀しおから.babelファむルを䜜成しようずしたしたそしおいく぀かのたわごずを远加したした。


_バグレポヌト_
D\ jetset \ JetSetApp> jest SaveData.test.js
FAIL __test __ / SaveData.test.js
●テストスむヌトの実行に倱敗したした

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:

D:\jetset\JetSetApp\node_modules\expo-file-system\build\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as FileSystem from './FileSystem';
                                                                                                ^

SyntaxError: Unexpected token *

  1 | import React, { Component } from 'react'
  2 | import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'
> 3 | import { documentDirectory, getInfoAsync, readDirectoryAsync, readAsStringAsync, writeAsStringAsync, deleteAsync } from 'expo-file-system';
    | ^
  4 |
  5 | /**
  6 |  * This class primarily serves to handle files within the phone system so that results can be stored

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at Object.<anonymous> (app/resources/SaveData/SaveData.js:3:1)

テストスむヌト1぀倱敗、合蚈1぀
テスト合蚈0
スナップショット合蚈0
時間3.509秒
/SaveData.test.js/iに䞀臎するすべおのテストスむヌトを実行したした。


_ babel.config.js _
module.exports = functionapi{
api.cachetrue;
戻る {
プリセット['babel-preset-expo']、
};
};


_ package.json _
{{
"main" "node_modules / expo / AppEntry.js"、
「スクリプト」{
「スタヌト」「゚キスポスタヌト」、
"android" "expo start --android"、
"ios" "expo start --ios"、
"web" "expo start --web"、
「むゞェクト」「゚クスポむゞェクト」、
「テスト」「冗談」
}、
「冗談」{
「プリセット」「react-native」
}、
「䟝存関係」{
"expo" "^ 34.0.1"、
"expo-file-system" "^ 6.0.2"、
"expo-mail-composer" "^ 6.0.0"、
"モヌメント" "^ 2.24.0"、
"react" "16.8.3"、
"react-dom" "^ 16.8.6"、
"react-native" " https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz "、
"react-native-gesture-handler" "^ 1.3.0"、
"react-native-selection-group" "^ 1.1.2"、
"react-native-web" "^ 0.11.4"
}、
"devDependencies"{
"@ babel / core" "^ 7.6.2"、
"@ babel / preset-env" "^ 7.6.2"、
"babel-jest" "^ 24.9.0"、
"babel-preset-expo" "^ 6.0.0"、
"jest" "^ 24.9.0"、
"prop-types" "^ 15.7.2"、
"react-native-dismiss-keyboard" "^ 1.0.0"、
"react-native-modal-datetime-picker" "^ 7.5.0"、
"react-navigation" "^ 3.12.1"
}、
「プラむベヌト」true
}

参考たでに、NODE_ENV = "test"が蚭定されおいないずビルドシステム党䜓がうたく動䜜しなかったように、これに察する本圓にばかげた解決策を芋぀けたず思いたす。

React Jestの新しいバヌゞョンでは、したがっおpackage.jsonに組み蟌たれおいるため、テストスクリプトは次のようになりたす。
"test": "react-scripts test"
それ以倖の
"test": "jest"

React Jestの新しいバヌゞョンでは、したがっおpackage.jsonに組み蟌たれおいるため、テストスクリプトは次のようになりたす。
"test": "react-scripts test"
それ以倖の
"test": "jest"

どうもありがずう、それは私にずっお問題を解決したした

LOTを詊した埌、私にずっおの問題
.babelrcファむルに"transform-es2015-modules-commonjs",がありたせん

{
  "presets": ["next/babel"],
  "plugins": [
    ["styled-components", { "ssr": true, "displayName": true, "preprocess": false } ],
    "transform-flow-strip-types",
    "jsx-control-statements",
    "import-glob",
    "transform-es2015-modules-commonjs",
    [
      "import",
      {
        "libraryName": "antd",
        "style": "css"
      }
    ]
  ]
}

"jest" "^ 24.9.0"、
"babel-jest" "23.6.0"、

あなたのjestずbabel-jestを曎新しおみおください

.babelrc名前をbabel.config.jsに倉曎し、Babel7にアップグレヌドしおも、以前ず同じ゚ラヌが発生したす。 私のbabel.config.jsファむル

module.exports = function (api) {
  api.cache(true);

  const presets = ["@babel/preset-env"];

  return {
    presets
  };
}

@babel/preset-reactをむンストヌルしお、 babel.config.jsファむルに远加したした。 ゚ラヌを修正したした。

これで問題が修正されたした。@ babel / prefix-envをむンストヌルしおbabel.config.jsに远加するず、修正されたした。

ありがずう@jmayergit

babel.rcファむルをbabel.config.jsファむルに倉曎したしたが、機胜したせんでした。 それから私はこの答えを芋たした https 
むンポヌトプラグむンがある堎合は、テスト、開発、本番環境のプラグむンを分離したす。

私のbabel.config.jsファむルは次のようになりたす。

module.exports = {
  presets: [
    [
      'next/babel',
    ],
  ],
  env: {
    test: {

    },
    dev: {
      plugins: [
        ['import', { libraryName: 'antd', style: 'css' }],
      ],
    },
    production: {
      plugins: [
        ['import', { libraryName: 'antd', style: 'css' }],
      ],
    },
  },
};

私も5日からこの゚ラヌに苊しんでいたす

    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:

    SyntaxError: C:\Users\SK-PC\Desktop\React-Course\expansify\src\test\components\MyNavbar.test.js: Unexpected token (5:28)

      3 | import { MyNavbar } from '../../components/MyNavbar'
      4 | test("Should return MyNavbar component", () => {
    > 5 |     const wrapper = shallow(<MyNavbar />)
        |                             ^
      6 |     expect(wrapper.find('.navbar-brand').find('kbd').text()).toBe("Expensify")
      7 |     // const renderer = new ReactShallowRenderer()
      8 |     // renderer.render(<MyNavbar />)

      at Parser._raise (node_modules/@babel/parser/src/parser/location.js:241:45)
      at Parser.raiseWithData (node_modules/@babel/parser/src/parser/location.js:236:17)
      at Parser.raise (node_modules/@babel/parser/src/parser/location.js:220:17)
      at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:149:16)
      at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1144:20)
      at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:539:23)
      at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:519:21)
      at Parser.parseExprOps (node_modules/@babel/parser/src/parser/expression.js:311:23)
      at Parser.parseMaybeConditional (node_modules/@babel/parser/src/parser/expression.js:263:23)
      at Parser.parseMaybeAssign (node_modules/@babel/parser/src/parser/expression.js:211:21)

 PASS  src/test/reducers/filters.test.js

Test Suites: 1 failed, 5 passed, 6 total
Tests:       29 passed, 29 total
Snapshots:   0 total
Time:        12.144s
Ran all test suites.

@fullstacksk

React Jestの新しいバヌゞョンでは、したがっおpackage.jsonに組み蟌たれおいるため、テストスクリプトは次のようになりたす。
"test": "react-scripts test"
それ以倖の
"test": "jest"

次の堎所でドキュメントを読むこずができたす。
https://jestjs.io/docs/en/tutorial-react
https://create-react-app.dev/docs/running-tests/#docsNav

@ catmans1
create-react-appやreact-scriptsのような䟝存関係をむンストヌルしおいたせん。
それは機胜したすか
"test": "react-scripts test"
それ以倖の
"test": "jest"

envずreactでオプションをテストするためにbabel-preset-jestを䜿甚したずき、これは機胜しおいたす。 babel-jeastを削陀したした。

私のために働いた babel.config.js 「@babel / preset-react」を含める

https://medium.com/@audreyhal/how -to-solve-jest-error-with-create-react-app-part-1-80f33aa1661a

愚かな間違いを犯し、最初のテストファむルを.tsx拡匵子ではなく.ts曞き蟌んだ埌、この゚ラヌが発生したした。 元の問題からはほど遠いですが、誰かに圹立぀かもしれたせんが😄

このペヌゞは圹に立ちたしたか
0 / 5 - 0 評䟡