Тестовые костюмы не прошли с SyntaxError: Неожиданный токен «экспорт» реагирует на машинописный текст с использованием шутки

я настраиваю шутку и фермент в своем проекте реактивного машинописного текста. В этом проекте я не использую Babel.

Я попытался запустить базовый компонент, и он работает хорошо.

После этого я добавил еще один компонент и добавил в этот компонент нашу пользовательскую библиотеку, основанную на реакции на машинописный текст (cc-react-common-lib).

когда я включаю cc-react-common-lib, шутка выдает следующую ошибку

SyntaxError: Неожиданный токен "экспорт"

 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:

    /home/convertcart/projects/intelli-blocks/node_modules/cc-react-common-lib/lib/index.js:1
    export { default as TableSpaced } from './general/table-spaced';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      1 | /* eslint-disable jsx-a11y/control-has-associated-label */
      2 | import React, { useState, useEffect } from 'react';
    > 3 | import {
        | ^
      4 |   TextField,
      5 |   useAjaxForm,
      6 |   Spacer,

Я пытаюсь решить эту ошибку за последнюю неделю, но не могу найти решение

jest.config.js:

module.exports = {
  // The root of your source code, typically /src
  // `<rootDir>` is a token Jest substitutes
  roots: ['<rootDir>'],

  // Jest transformations -- this adds support for TypeScript
  // using ts-jest
  // transform: {
  //   "^.+\\.tsx?$": "ts-jest"
  // },
  preset: 'ts-jest',
  // maxConcurrency:30,
  // Runs special logic, such as cleaning up components
  // when using React Testing Library and adds special
  // extended assertions to Jest
  // setupFilesAfterEnv: [
  //   "@testing-library/react/cleanup-after-each",
  //   "@testing-library/jest-dom/extend-expect"
  // ],

  // Test spec file resolution pattern
  // Matches parent folder `__tests__` and filename
  // should contain `test` or `spec`.
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',

  // Module file extensions for importing
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  snapshotSerializers: ['enzyme-to-json/serializer'],
  setupFilesAfterEnv: ['<rootDir>/setupEnzyme.ts'],
};

setupEnzyme.js:

/* eslint-disable import/no-extraneous-dependencies */
import Enzyme from 'enzyme';
import ReactSixteenAdapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new ReactSixteenAdapter() });

Обновление: когда я добавляю следующие строки в файл jest.confi.js

transform: {
    '^.+\\.tsx?$': 'babel-jest',
  },

Приходит следующее сообщение об ошибке:

● Test suite failed to run

    SyntaxError: /home/convertcart/projects/intelli-blocks/client/__tests__/editblock.test.tsx: Support for the experimental syntax 'jsx' isn't currently enabled (8:29):

       6 | console.log("Edit block test");
       7 | it('Renders and Simulates Click Event ', () => {
    >  8 |     const Wrapper = shallow(<EditBlock />);
         |                             ^
       9 |     const checkbox = () => Wrapper.find({ type: 'checkbox' });
      10 |     expect(checkbox().props().checked).toBe(false);
      11 |     checkbox().simulate('change', { target: { checked: true } });

    Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
    If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.

      at Parser._raise (../node_modules/@babel/parser/src/parser/error.js:60:45)
      at Parser.raiseWithData 

person PrakashT    schedule 10.09.2020    source источник
comment
Jest 25 должен иметь встроенную поддержку ESM stackoverflow.com/a/61652773/2312051   -  person Denis Tsoi    schedule 03.11.2020
comment
Отвечает ли это на ваш вопрос? Поддерживает ли Jest импорт/экспорт ES6?   -  person Denis Tsoi    schedule 03.11.2020
comment
@DenisTsoi спасибо за ваш комментарий. этот ответ бесполезен. и я обновил свой вопрос и, пожалуйста, проверьте   -  person PrakashT    schedule 03.11.2020


Ответы (1)


если вы запускаете тест через плагин редактора кода, попробуйте настроить команду тестирования плагина в редакторе, чтобы убедиться, что плагин выполняет правильную команду.

например Я использую vscode, плагин jestrunner и менеджер пакетов пряжи. поэтому я включил следующую строку в файл settings.json моего рабочего пространства:

{
    "jestrunner.jestCommand": "yarn react-scripts test"
}

та же ошибка устранена. надеюсь, это сработает для вас :)

person user16545648    schedule 28.07.2021