Create React App + Ant Design测试报错:TypeError: window.matchMedia is not a function
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
Create/Update the Test Setup File
If you don’t already have one, create asetupTests.jsfile in your project’ssrcdirectory. This file runs automatically before your tests execute, so it’s perfect for adding global API mocks.Add ResizeObserver Mock
Paste this mock implementation intosetupTests.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() {} };Re-Run Your Tests
Now go ahead and run your test suite again withnpm testoryarn 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.jsis in thesrcdirectory (create-react-app only auto-loads it from there)
内容的提问来源于stack exchange,提问作者hsngdr

