最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Issue Setting Up babel-jest with React - Support for the experimental syntax 'jsx' isn't curre

programmeradmin1浏览0评论

I am having an issue running tests with jest and RTL.

In my jest.config.js I have this:

const config = {
  transform: {
    ".*": "babel-jest",
    "^.+\\.(gql|graphql)$": "jest-transform-graphql",
  },
  rootDir: './',
  verbose: true,
  testMatch: ['**/__tests__/**/*.(js|jsx|ts|tsx)'],
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleDirectories: ['node_modules'],
  moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node', 'gql'],
  moduleNameMapper: {
    '^components/(.*)$': '<rootDir>/projects/ui/src/components/$1',
  },
  transformIgnorePatterns: [
    '<rootDir>/node_modules',
    '\\.gql$', 
    '\\.graphql$',
  ],
  testPathIgnorePatterns: [
    '<rootDir>/node_modules',
    '\\.gql$', 
    '\\.graphql$',
  ],
  testEnvironment: 'jsdom',
};

module.exports = config;

My jest.setup.js file

import '@testing-library/jest-dom';

My babel.config.js

module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    ["@babel/preset-react", { runtime: "automatic" }],
  ],
   plugins: [
    '@babel/plugin-syntax-jsx',
    '@babel/plugin-transform-runtime',
  ]
};

My Single Test File

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import WelcomePopup from 'components/WelcomePopup/WelcomePopup';

describe('Popup Controller', () => {
  const renderWelcomePopup = (props = {}) => {
    const utils = render(<WelcomePopup {...props} />);
    const openModalButton = screen.getByText('Open Modal');
    return { ...utils, openModalButton };
  };

  describe('determines if the welcome popup should be displayed', () => {
    it('should show the welcome popup when user redirected to CA', () => {
      const { container } = renderWelcomePopup();
      // Check that the popup is initially hidden or not rendered
      expect(container.querySelector('.popup')).toBeNull();

      // Simulate user action or state change to show popup
      fireEvent.click(screen.getByText('Open Modal'));
      expect(container.querySelector('.popup')).toBeInTheDocument();
    });
  });
});

Then I run

npm run test -- __tests__/spec/WelcomePopup/WelcomePopup.spec.js

But even though in my jest config I have transform for babel-jest I see this error:

 FAIL  __tests__/spec/WelcomePopup/WelcomePopup.spec.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see  for how to enable it.
     • If you are trying to use TypeScript, see 
     • 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:
    
    For information about custom transformations, see:
    

    Details:

    SyntaxError: __tests__/spec/WelcomePopup/WelcomePopup.spec.js: Support for the experimental syntax 'jsx' isn't currently enabled (7:26):

       5 | describe('Popup Controller', () => {
       6 |   const renderWelcomePopup = (props = {}) => {
    >  7 |     const utils = render(<WelcomePopup {...props} />);
         |                          ^
       8 |     const openModalButton = screen.getByText('Open Modal');
       9 |     return { ...utils, openModalButton };
      10 |   };

TLDR ERROR: Support for the experimental syntax 'jsx' isn't currently enabled (7:26):

Dependencies installed relevant for tests:

  "@babel/cli": "^7.26.4",
        "@babel/core": "^7.26.0",
        "@babel/preset-env": "^7.26.0",
        "@babel/preset-react": "^7.26.3",
        "@testing-library/jest-dom": "^6.6.3",
        "@testing-library/react": "^11.2.7",
        "@testing-library/user-event": "^14.6.0",
        "babel-jest": "26.6.3",
        "jest": "26.6.3",
        "jest-environment-jsdom": "26.6.2",
        "jest-transform-graphql": "^2.1.0"

Why is my jest config not able to parse/recognize JSX properly? The app itself does just not JEST.

I also have strange behavior when running jest with this command instead: BABEL_SHOW_CONFIG_FOR=__tests__/spec/WelcomePopup/WelcomePopup.spec.js npx jest

OUTPUT:

Test suite failed to run
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){# Query for Systematic Employee Discount work
                                                                                             ^

    SyntaxError: Invalid or unexpected token

      1 | import { UserProfileQuery } from 'gql/queries/user/userProfileQuery.gql';
    > 2 | 
        | ^


Babel configs on "__tests__/spec/WelcomePopup/WelcomePopup.spec.js" (ascending priority):
programmatic options from babel-jest
{
  "assumptions": {},
  "caller": {
    "name": "babel-jest",
    "supportsDynamicImport": false,
    "supportsExportNamespaceFrom": false,
    "supportsStaticESM": false,
    "supportsTopLevelAwait": false
  },
  "compact": false,
  "sourceMaps": "both",
  "filename": "__tests__/spec/WelcomePopup/WelcomePopup.spec.js",
  "targets": {},
  "cloneInputAst": true,
  "babelrc": false,
  "configFile": false,
  "browserslistConfigFile": false,
  "passPerPreset": false,
  "envName": "test",
  "rootMode": "root",
  "plugins": [
    "@babel/plugin-syntax-jsx",
    "@babel/plugin-transform-optional-chaining",
    "@babel/plugin-transform-object-rest-spread",
    "@babel/plugin-transform-class-properties",
    "@babel/plugin-transform-runtime"
  ],
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ],
    [
      "@babel/preset-react",
      {
        "runtime": "automatic"
      }
    ],
    "babel-preset-jest/index.js"
  ]
}
-----End Babel configs-----

So it seems that it can find my babel.config.js depending on how I run jest. But I would like to run it using my own npm script not npx.

Any help appreciated.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论