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

React项目集成Jest+Enzyme测试失败,寻求解决方法

Troubleshooting Enzyme + Jest Setup for React Project

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.js file
  • 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:12:31