React项目集成Jest+Enzyme测试失败,寻求解决方法
Let's walk through fixing your test environment issues step by step. Based on your config files, there are a few key gaps that are likely causing the error when running yarn test:
Key Issues in Your Current Setup
- Enzyme's React 16 adapter isn't initialized in your test environment
- Jest isn't configured to load your
setupTests.jsfile - Missing Babel configuration to properly transpile React/ES6+ code
- Mismatched versions between Jest and babel-jest dependencies
Step-by-Step Fixes
1. Update setupTests.js to Initialize Enzyme Adapter
Your current setup file only mocks matchMedia, but Enzyme needs explicit configuration to work with React 16. Modify the file like this:
import Enzyme from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; // Initialize Enzyme with React 16 adapter Enzyme.configure({ adapter: new Adapter() }); // Keep your existing matchMedia mock global.matchMedia = global.matchMedia || function() { return { matches: false, addListener() {}, removeListener() {}, }; };
2. Configure Jest to Load setupTests.js
Update your jest.config.js to specify the setup file that runs before tests start:
module.exports = { moduleFileExtensions: ['js', 'jsx', 'json'], transform: { '^.+\\.(js|jsx)?$': 'babel-jest' }, transformIgnorePatterns: ['<rootDir>/node_modules/'], // Add this line to load your setup file setupFilesAfterEnv: ['<rootDir>/setupTests.js'] };
Also, remove the duplicate jest field from your package.json to avoid configuration conflicts—we'll rely solely on jest.config.js.
3. Add a Babel Configuration File
Babel-jest needs a preset to transpile React code. Create a .babelrc file in your project root:
{ "presets": ["react-app"], "plugins": [ "transform-class-properties", "syntax-dynamic-import" ] }
If you don't have babel-preset-react-app installed, add it via yarn:
yarn add --dev babel-preset-react-app
4. Sync Jest Dependency Versions
Your jest (23.4.2) and babel-jest (23.6.0) versions don't match, which can cause compatibility bugs. Upgrade them to the same version:
yarn add --dev jest@23.6.0 jest-cli@23.6.0 babel-jest@23.6.0
5. Verify with a Simple Test
Create a basic test file (e.g., App.test.js) to confirm the setup works:
import React from 'react'; import { shallow } from 'enzyme'; import App from './App'; // Replace with your root component test('Root component renders without crashing', () => { shallow(<App />); });
Run yarn test—this should execute successfully if the setup is fixed.
内容的提问来源于stack exchange,提问作者Rajan Lagah

