Webpack构建React项目后Jest测试报错,求正确配置方案
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 = {};
4. Update Your Test Code (Optional but Recommended)
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

