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

Create React App + Ant Design测试报错:TypeError: window.matchMedia is not a function

Fixing Ant Design Row Component Test Errors in Create-React-App

Hey there, I’ve run into this exact issue before with Ant Design’s Row component breaking tests in create-react-app projects—let’s get this sorted out for you!

The root cause here is that Ant Design’s Row (and related grid components) rely on the ResizeObserver browser API to handle responsive layout logic. Unfortunately, the JSDOM environment that create-react-app uses for testing doesn’t include a native implementation of this API by default, which triggers those errors when you add the Row component.

Step-by-Step Solution

  1. Create/Update the Test Setup File
    If you don’t already have one, create a setupTests.js file in your project’s src directory. This file runs automatically before your tests execute, so it’s perfect for adding global API mocks.

  2. Add ResizeObserver Mock
    Paste this mock implementation into setupTests.js:

    // Mock ResizeObserver to support Ant Design grid components
    global.ResizeObserver = class ResizeObserver {
      constructor(callback) {
        this.callback = callback;
      }
    
      observe(element) {
        // Simulate a basic resize event callback
        this.callback([{ target: element }], this);
      }
    
      unobserve(element) {}
    
      disconnect() {}
    };
    
  3. Re-Run Your Tests
    Now go ahead and run your test suite again with npm test or yarn test. The errors from the Row component should disappear, and all your existing tests (for DatePicker, Button, Title) will still pass.

Why This Works

This mock provides a minimal, functional implementation of ResizeObserver that Ant Design’s grid components expect. It doesn’t replicate every detail of the real browser API, but it’s enough to prevent the test environment from throwing errors during rendering.

If you’re still seeing issues after this, double-check:

  • That you’ve correctly imported antd/dist/antd.min.css (which you already have in App.js)
  • That your setupTests.js is in the src directory (create-react-app only auto-loads it from there)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:19:09