Jest: واجهت Jest رمزًا مميزًا غير متوقع مع تطبيق React

تم إنشاؤها على ٣١ أغسطس ٢٠١٨  ·  42تعليقات  ·  مصدر: facebook/jest

الحب الدعابة؟ يرجى النظر في دعم مجموعتنا: https://opencollective.com/jest/donate

🐛 تقرير الشوائب

عند محاولة إجراء الاختبارات باستخدام Jest في تطبيق React ، يظهر لي خطأ 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"]
    }
  }
}

لإعادة إنتاج

خطوات إعادة إنتاج السلوك:

  • قم بتثبيت Jest بـ yarn add --dev babel-jest babel-core@^7.0.0-0 @babel/core
  • قم بإنشاء اختبار
  • قم بتشغيل 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 أيام ، اكتشفت الحلول لهذه المشكلة.
هناك حلان لهذا:

الحل 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 = تتطلب ("./ env-config.js") ؛

module.exports = {
الإعدادات المسبقة: [
[
"التالي / بابل"،
{
"preet-env": {
useBuiltIns: "دخول"
}
}
]
] ،
المكونات الإضافية: [
["عناصر النمط"، {ssr: true، displayName: true، preprocess: false}]،
[
"وحدة الحل"،
{
جذر: ["./"]
}
]
] ،
env: {
ديف: {
المكونات الإضافية: [
["تعريف التحويل" ، البيئة] ،
["وحدة الحل" ، {الجذر: ["./"]}] ،
"تحويل-ديكور-تراث" ،
"تحويل-فئة-خصائص"
]
} ،
يبني: {
المكونات الإضافية: [
["تعريف التحويل" ، بيئات] ،
["وحدة الحل" ، {الجذر: ["./"]}] ،
"تحويل-ديكور-تراث" ،
"تحويل-فئة-خصائص"
]
} ،
إنتاج: {
الإعدادات المسبقة: [
[
"minify" ، // لماذا أضف minify هنا ، نحن نشغل uglify على حزم التعليمات البرمجية بأكملها
{
يفسد: خطأ ،
تقييم: خطأ
}
]
] ،
المكونات الإضافية: [
["تعريف التحويل" ، البيئة] ،
["@ babel / plugin-offer-decorators"، {legacy: true}]،
["@ babel / plugin-offer-class-properties"، {loose: true}]،
["وحدة محلل"، {الجذر: ["./"]}]
] ،
التعليقات: خطأ ،
مضغوط: صحيح ،
مصغر: صحيح
}
}
} ؛
""
آمل أن يؤدي هذا إلى تجاوز هذه المشكلة يا رفاق. يشجع.

ال 42 كومينتر

لدي نفس المشكلة أيضا.

نفس المشكلة هنا.

نفس المشكلة هنا .. أكثر تعقيدًا بعض الشيء حيث أعمل مع monorepo.

fabioSalimbenihoaiduyitmikedloss لقد أجريت React و React Native ( Jest و enzyme ) تمر في Lerna monorepo باستخدام Babel 7.

تحتاج إلى استخدام تكوين Babel الجديد مع babel.config.js إذا كنت تعمل في monorepo: https://babeljs.io/docs/en/v7-migration.

هذا هو babel.config.js الخاص بي لجذر monorepo:

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

هكذا يبدو babel.config.js الخاص بي مقابل webApp1 أحد تطبيقات monorepo:

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 = {};

ستحتاج أيضًا إلى إضافة بعض مكونات Babel الإضافية وإصدار babel-core كـ devDependencies في package.json لكل تطبيق:

        ...
        "@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 أيام ، اكتشفت الحلول لهذه المشكلة.
هناك حلان لهذا:

الحل 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 = تتطلب ("./ env-config.js") ؛

module.exports = {
الإعدادات المسبقة: [
[
"التالي / بابل"،
{
"preet-env": {
useBuiltIns: "دخول"
}
}
]
] ،
المكونات الإضافية: [
["عناصر النمط"، {ssr: true، displayName: true، preprocess: false}]،
[
"وحدة الحل"،
{
جذر: ["./"]
}
]
] ،
env: {
ديف: {
المكونات الإضافية: [
["تعريف التحويل" ، البيئة] ،
["وحدة الحل" ، {الجذر: ["./"]}] ،
"تحويل-ديكور-تراث" ،
"تحويل-فئة-خصائص"
]
} ،
يبني: {
المكونات الإضافية: [
["تعريف التحويل" ، بيئات] ،
["وحدة الحل" ، {الجذر: ["./"]}] ،
"تحويل-ديكور-تراث" ،
"تحويل-فئة-خصائص"
]
} ،
إنتاج: {
الإعدادات المسبقة: [
[
"minify" ، // لماذا أضف minify هنا ، نحن نشغل uglify على حزم التعليمات البرمجية بأكملها
{
يفسد: خطأ ،
تقييم: خطأ
}
]
] ،
المكونات الإضافية: [
["تعريف التحويل" ، البيئة] ،
["@ babel / plugin-offer-decorators"، {legacy: true}]،
["@ babel / plugin-offer-class-properties"، {loose: true}]،
["وحدة محلل"، {الجذر: ["./"]}]
] ،
التعليقات: خطأ ،
مضغوط: صحيح ،
مصغر: صحيح
}
}
} ؛
""
آمل أن يؤدي هذا إلى تجاوز هذه المشكلة يا رفاق. يشجع.

GeorgianSorinMaxim المشكلة هي أن تطبيق الدعابة الخاص بي يتجاهل ملف .babelrc ، والتغيير إلى babel.config.js سيحل المشكلة ، لكنني قمت بحلها على أي حال ، إجابتي أعلى من هذا التعليق.

بفضلGeorgianSorinMaximhoaiduyit في النهاية لقد تحل ببساطة عن طريق إنشاء محول مخصص لبابل-المزاح. لا توجد تغييرات أخرى عند الحاجة.

يبدو أن Babel 7 يتطلب babel.config.js للعمل بشكل صحيح ، استخدم ذلك بدلاً من babelrc

لا يزال يعتمد babel-jest في babel-core من Babel 6 ، إذا كنت تريد استخدام Babel 7 ، فيمكنك استخدامه
هذا متحولة 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 حل المشكلة :)

alexindigohoaiduyit كيف جميعًا هذا في العالم حول babel.config.js ؟ في مواجهة نفس المشكلة وإيجاد الحلول الخاصة بك ، كنت أفكر في نفسي ... _ "حسنًا ، هناك طريقة لن تعمل هذه الطريقة ولكن سأحاول على أي حال." ولكن من المؤكد أنها فعلت ذلك. شكرا

تكوين Jest & enzyme: أضف الكود التالي في 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 = تتطلب ('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 . إصلاح الخطأ.

لم يتم اكتشاف ملف 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- إذا كان لديك خطأ في الكلمة الرئيسية "توقع" في اختبارك ، فما عليك سوى تشغيل npm install -D chai واستيراد وظيفة توقع في كود الاختبار الخاص بك مثل import { expect } from 'chai';

إذا استمر ظهور الخطأ ، فحاول تثبيت تبعيات بابل مثل npm install -D @babel/core @babel/preset-env @babel/preset-react

أتمنى أن يساعدك هذا.

بعد 3 أيام ، اكتشفت الحلول لهذه المشكلة.
هناك حلان لهذا:

الحل 1:

يمكنك تغيير اسم ملفك من .babelrc إلى babel.config.js ، وسيعمل هذا.

بلدي الحل:

لم يكن لدي ملف .babelrc لذلك اعتقدت أن القيام بالعكس يجب أن يعمل أيضًا وأنشأت ملف .babelrc باستخدام المعلومات المحددة مسبقًا من babel.config.js بدلاً من ذلك. (لقد أنشأت ملفًا إضافيًا ، ولم أعد تسمية الملف الأصلي)
عند تشغيل الاختبار مرة أخرى ، تلقيت خطأ جديدًا: 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; (الفاصلة المنقوطة في النهاية)

مجموعتي. 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 babel-jest transform / transpile jest في jest.config.js

بعد 3 أيام ، اكتشفت الحلول لهذه المشكلة.
هناك حلان لهذا:

الحل 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 = {
  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
    }
  }
};

آمل أن يؤدي هذا إلى تجاوز هذه المشكلة يا رفاق. يشجع.

تكس لطريقتك ~ هذه الطريقة يمكن أن تصلح مشكلتي بشكل صحيح!

مرحباً - لقد جربت عدة أشياء في هذا الموضوع ، لكن لا شيء يبدو أنه يعمل. الخطأ الرئيسي هو b / c غريب يبدو أنه يشير إلى أرقام الأسطر التي لا معنى لها ، مثل الكود المصدري والشفرة الفعلية التي تحاول التشغيل لا تتماشى ..

هذا الخطأ ، واجه Jest رمزًا مميزًا غير متوقع ، ويبقى. أنا في Jest> 24 ، لا يوجد نوع نص برمجي ، إنه تطبيق تم طرده مؤخرًا (منذ 6 أشهر ~). لم يساعد مسح ذاكرة التخزين المؤقت وإزالة node_modules. ربما يمكن لشخص ما أن يشرح بالضبط ما هو التكوين الذي يجب أن يكون في مكانه حتى تتمكن المزاح من التحويل والتشغيل بشكل صحيح وما يلمح خطأي الدقيق ...

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 ، فإن إضافة transformignorepatterns إلى package.json الخاص بك لن يحل المشكلة حيث يمكن فقط تغيير تكوينات jest معينة في package.json عند استخدام CRA.

واجهت مشكلات مع Jest في التقاط مكتبة داخلية ، وكان Jest يعرض أخطاء "رمز مميز غير متوقع" أينما حصلت على وارداتي من هذه المكتبة.

لحل هذه المشكلة ، يمكنك تغيير البرنامج النصي للاختبار إلى ما يلي:
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",

مرحبًا بالجميع ، كنت أعاني من أجل إجراء اختبار الوحدة مع مشروعي الصغير الذي يسمى JetSet وكتبت في React Native. لقد بحثت لمدة يومين لحل هذه المشكلة ، وحاولت تعديل أشياء مثل 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 (صحيح) ؛
إرجاع {
الإعدادات المسبقة: ["babel-preset-expo"] ،
} ؛
} ؛


_ package.json _
{
"main": "node_modules / expo / AppEntry.js"،
"نصوص": {
"البدء": "بداية المعرض" ،
"android": "expo start --android"،
"ios": "expo start --ios"،
"الويب": "expo start --web"،
"إخراج": "إخراج المعرض" ،
"test": "jest"
} ،
"دعابة": {
"ضبط مسبق": "تفاعل أصلي"
} ،
"التبعيات": {
"إكسبو": "^ 34.0.1" ،
"نظام ملفات المعرض": "^ 6.0.2"،
"expo-mail-composer": "^ 6.0.0"،
"اللحظة": "^ 2.24.0"،
"رد فعل": "16.8.3"،
"رد فعل دوم": "^ 16.8.6"،
"رد فعل أصلي": " https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz " ،
"معالج الإيماءات التفاعلية": "^ 1.3.0"،
"تفاعل-أصلي-اختيار-مجموعة": "^ 1.1.2"،
"تفاعل-أصلي-ويب": "^ 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"،
"أنواع العناصر": "^ 15.7.2"،
"تفاعل-أصلية-رفض-لوحة المفاتيح": "^ 1.0.0"،
"منتقي التفاعل الأصلي-النموذج-التاريخ والوقت": "^ 7.5.0" ،
"رد فعل التنقل": "^ 3.12.1"
} ،
"خاص": صحيح
}

لمعلوماتك ، أعتقد أننا انتهينا من إيجاد حل سخيف حقًا لهذا الأمر ، مثل نظام البناء بأكمله لم يكن يتصرف بشكل جيد إذا لم يتم تعيين NODE_ENV = "test".

في الإصدارات الأحدث من React Jest مدمج في package.json يجب أن يكون نص الاختبار
"test": "react-scripts test"
بدلا من
"test": "jest"

في الإصدارات الأحدث من React Jest مدمج في package.json يجب أن يكون نص الاختبار
"test": "react-scripts test"
بدلا من
"test": "jest"

شكرًا جزيلاً ، لقد أدى ذلك إلى حل المشكلة بالنسبة لي!

بعد تجربة الكثير ، المشكلة بالنسبة لي:
مفقود "transform-es2015-modules-commonjs", في ملف .babelrc

{
  "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"،

حاول تحديث الدعابة و 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 / preset-env وأضفته إلى babel.config.js وتم إصلاحه

شكرا jmayergit

لقد قمت بتغيير ملف babel.rc إلى ملف babel.config.js ولكنه لم يكن يعمل معي. ثم رأيت هذه الإجابة: https://stackoverflow.com/questions/58470062/test-jest-with-babel-plugin-import
إذا كان لدى أحدهم مكونات إضافية للاستيراد ، فافصل المكونات الإضافية لبيئات الاختبار والتطوير والإنتاج.

يبدو ملف 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.

تضمين التغريدة

في الإصدارات الأحدث من 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

هههههههههههه
لم أقم بتثبيت التبعيات مثل إنشاء تطبيق تفاعل أو نصوص تفاعلية.
هل ستعمل؟
"test": "react-scripts test"
بدلا من
"test": "jest"

إنها تعمل الآن ، عندما استخدمت babel-preset-jest لاختبار الخيار مع env والتفاعل. لقد قمت بإزالة بابل جيست.

عملت من أجلي: تضمين "@ babel / preset-response" بسعر babel.config.js

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

لقد رأيت هذا الخطأ بعد ارتكاب خطأ غبي وكتابة أول ملف اختباري بامتداد .ts بدلاً من .tsx . بعيدًا عن الإصدار الأصلي ولكني على الرغم من أنه قد يكون مفيدًا لشخص ما

هل كانت هذه الصفحة مفيدة؟
0 / 5 - 0 التقييمات