简体   繁体   中英

Getting this error while testing my component using react testing library

Getting this error while testing

Error: matchMedia not present, legacy browsers require a 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";

I have my package.json as

"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"
    
  },

And also testsetup.js as

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

Create a separate(.).js file with beneath code and import it before(:) importing Slider (or any other crashing import). Solution found here: 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(),
  })),
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM