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

Webpack构建React项目后Jest测试报错,求正确配置方案

Fixing Jest Parsing Error with React JSX After Migrating from CRA to Webpack

Hey there, let's get your Jest tests running smoothly with your Webpack-built React project! The error you're seeing happens because Jest isn't properly transforming React's JSX syntax—even though you've set up Babel for Webpack, Jest needs its own clear configuration to handle these files. Here's how to fix it step by step:

1. Create/Update Your Jest Config File

Make sure your jest.config.js includes all necessary settings to handle React files and assets. Replace or add these configurations:

module.exports = {
  // Simulate a browser environment for React testing
  testEnvironment: 'jsdom',
  // Tell Jest to use babel-jest to transform JS/JSX files
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest',
  },
  // Mock CSS files since Jest doesn't process styles natively
  moduleNameMapper: {
    '\\.css$': '<rootDir>/__mocks__/styleMock.js',
  },
  // Add Jest DOM matchers for easier assertions (like toBeInTheDocument)
  setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
  // Recognize both .js and .jsx file extensions
  moduleFileExtensions: ['js', 'jsx'],
};

2. Make Babel Config Accessible to Jest

Your Webpack config has Babel presets, but Jest might not pick up those settings automatically. Let's create a shared Babel config so both tools can use it:
Either add this block to your package.json:

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

Or create a .babelrc file in your project root with:

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

3. Stub Out CSS Imports

Jest can't process CSS files directly, so we need to mock them. Create a __mocks__ folder in your project root, then add a styleMock.js file inside it with:

module.exports = {};

While your existing ReactDOM.render test will work once the config is fixed, using @testing-library/react's render method is more aligned with modern React testing best practices—it handles cleanup automatically too:

import { render, screen } from '@testing-library/react';
import App from './App';

it("renders without crashing", () => {
  render(<App />);
  // Optional: Add an assertion to verify content (example)
  // expect(screen.getByText('Welcome to My App')).toBeInTheDocument();
});

5. Run Your Tests

Now execute your test command again:

npm test

This should resolve the "unexpected token" error—Jest will now properly transform JSX via Babel and handle style imports with mocks.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 13:38:15