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 2021-07-08 20:49 fox_charon 阅读(1806) 评论(2) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 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的设计差异
· 三行代码完成国际化适配,妙~啊~