【问题标题】:Getting this error while testing my component using react testing library使用反应测试库测试我的组件时出现此错误
【发布时间】:2021-07-18 11:49:31
【问题描述】:

测试时出现此错误

错误:matchMedia 不存在,旧版浏览器需要 polyfill


      3 | import * as ConfigConstants from '../../constants/config'
      4 | import {animatePots} from '../helpers/common'
    > 5 | import Slider from "react-slick";
        | ^
      6 | import {connect, ReactReduxContext} from 'react-redux'
      7 | import "slick-carousel/slick/slick.css";
      8 | import "slick-carousel/slick/slick-theme.css";

我的 package.json 为

"scripts": {
    "start": "PORT=3002 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!amcharts)/\"",
    "eject": "react-scripts eject",
    "clear_jest": "jest --clearCache"
    
  },

还有 testsetup.js 为

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(),
    })),
  });

【问题讨论】:

  • 是什么让您认为 testsetup.js 会被加载? CRA 中文件的正确名称是 setupTests.js,它应该位于特定位置。
  • 它仍然无法正常工作@jonrsharpe

标签: javascript reactjs unit-testing jestjs integration-testing


【解决方案1】:

使用下面的代码创建一个单独的 (!) .js 文件,并在 (!) 导入 Slider(或任何其他崩溃导入)之前将其导入。在这里找到解决方案:https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

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(),
  })),
});

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2019-12-25
    • 2021-06-23
    相关资源
    最近更新 更多