Ant Design Pro V5 - jest 单元测试踩坑记录

1 Cannot find module '@/components/Footer' from 'src/pages/user/Login/index.jsx'

jest.config.js加上moduleNameMapper可解决。

参考:https://stackoverflow.com/questions/42629925/testing-with-jest-and-webpack-aliases

 

2 window.matchMedia is not a function

tests\setupTests.js需要加代码

```javascript
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
```

参考:https://stackoverflow.com/questions/39830580/jest-test-fails-typeerror-window-matchmedia-is-not-a-function

 

3 expect(...).toBeInTheDocument is not a function

需要jsdom环境,默认的node环境跑不了这个方法。

tests\setupTests.js

```javascript
// do some test init
// react-testing-library 将您的组件显示为document.body,
// 这将为 jest-dom 添加一个自定义断言
import '@testing-library/jest-dom';
```

参考:https://stackoverflow.com/questions/56547215/react-testing-library-why-is-tobeinthedocument-not-a-function

 

4 The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/en/configuration#testenvironment-string. Consider using the "jsdom" test environment.

需要jsdom环境。且对应文件的测试脚本需要用注释声明使用jsdom。

src\pages\Welcome.test.js加以下代码:

```javascript
/**
* @jest-environment jsdom
*/
```

 

5 [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.

@umijs/plugin-locale插件和jest不兼容。

 

6 TypeError: Cannot read property '@@initialState' of undefined

@umijs/plugin-initial-state插件和jest不兼容。

posted on   fox_charon  阅读(1806)  评论(2编辑  收藏  举报

编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示