Jest 测试失败:TypeError: window.matchMedia 不是函数 [英] Jest test fails : TypeError: window.matchMedia is not a function
本文介绍了Jest 测试失败:TypeError: window.matchMedia 不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的第一次前端测试体验.在这个项目中,我使用 Jest 快照测试并在我的组件中收到一个错误 TypeError: window.matchMedia is not a function
.
This is my first front-end testing experience. In this project, I'm using Jest snapshot testing and got an error TypeError: window.matchMedia is not a function
inside my component.
我浏览了 Jest 文档,找到了手动模拟"部分,但我还不知道如何做到这一点.
I go through Jest documentation, I found the "Manual mocks" section, but I have not any idea about how to do that yet.
推荐答案
Jest 文档现在有一个官方"解决方法:
The Jest documentation now has an "official" workaround:
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(),
})),
});
这篇关于Jest 测试失败:TypeError: window.matchMedia 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文