开玩笑的测试失败:TypeError:window.matchMedia不是一个函数 [英] Jest test fails : TypeError: window.matchMedia is not a function

查看:109
本文介绍了开玩笑的测试失败: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(),
  })),
});

模拟方法是不在JSDOM中实现

这篇关于开玩笑的测试失败:TypeError:window.matchMedia不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆