You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件Jest测试配置异常求助:意外令牌解析错误

React组件Jest测试环境配置问题求助

我正在项目中搭建React组件的Jest测试环境,配置过程中遇到两种运行方式均报错的问题:

1. IDE测试运行按钮执行报错

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.

2. 终端运行测试报错

终端执行测试时上述解析错误消失,但出现其他报错。

两种运行方式均无法正常执行测试,无法开展调试。

以下是我的相关配置与代码:

package.json 依赖及Jest配置

{
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.3.0",
    "babel-jest": "^28.1.3",
    "lodash-es": "^4.17.21",
    "react": "^18.0.0",
    "react-calendly": "^2.2.2",
    "react-i18next": "^11.8.8",
    "styled-components": "^5.3.1"
  },
  "devDependencies": {
    "@babel/preset-env": "^7.18.10",
    "@babel/preset-react": "^7.18.6",
    "@lexense/dv-deps": "^4.2.180",
    "@lexense/dv-lint": "^4.2.186",
    "@lexense/dv-prettier": "^4.2.180",
    "@lexense/dv-test": "^4.2.186",
    "babel-jest": "^28.1.3",
    "jest": "^28.1.3",
    "react-test-renderer": "^18.2.0"
  },
  "engines": {
    "node": "16.x",
    "yarn": ">=1.22.0"
  },
  "jest": {
    "testEnvironment": "jest-environment-jsdom",
    "transform": {
      "^.+\\.js$": "babel-jest"
    }
  }
}

babel.config.js 文件

module.exports = {
  presets: [
    '@babel/preset-env',
    ['@babel/preset-react', { runtime: 'automatic' }],
  ],
};
// Importing the jest testing library
import '@testing-library/jest-dom';

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

import Link from '../src/Link';

// afterEach function runs after each test suite is executed
afterEach(() => {
  cleanup(); // Resets the DOM after each test suite
});

describe('Link Component', () => {
  // Test 1
  test('Link Rendering', () => {
    render(<Link href={'www.facebook.com'} text={'Facebook'} />);
    const link = screen.getByTestId('link');
    expect(link).toBeInTheDocument();
  });
});

希望了解相关技术的朋友提供帮助,提前感谢。

内容的提问来源于stack exchange,提问作者Anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:51:13