【问题标题】:matchMedia not present when testing create-react-app component which contain react-slick?测试包含 react-slick 的 create-react-app 组件时 matchMedia 不存在?
【发布时间】:2023-03-06 03:16:01
【问题描述】:

我尝试为我现有的项目创建测试文件,该项目由

https://github.com/facebookincubator/create-react-app

但是当我运行npm test a时出现这个错误

FAIL  src/__tests__/movie_single/MovieSingle-test.js
  ● Test suite failed to run

    matchMedia not present, legacy browsers require a polyfill

      at Object.MediaQueryDispatch (node_modules/enquire.js/dist/enquire.js:226:19)
      at node_modules/enquire.js/dist/enquire.js:291:9
      at Object.<anonymous>.i (node_modules/enquire.js/dist/enquire.js:11:20)
      at Object.<anonymous> (node_modules/enquire.js/dist/enquire.js:21:2)
      at Object.<anonymous> (node_modules/react-responsive-mixin/index.js:2:28)
      at Object.<anonymous> (node_modules/react-slick/lib/slider.js:19:29)
      at Object.<anonymous> (node_modules/react-slick/lib/index.js:3:18)
      at Object.<anonymous> (src/components/movie_single/MovieDetailsBox.js:4:45)
      at Object.<anonymous> (src/components/movie_single/MovieSingle.js:3:50)
      at Object.<anonymous> (src/__tests__/movie_single/MovieSingle-test.js:3:46)
      at process._tickCallback (internal/process/next_tick.js:103:7)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.642s
Ran all test suites matching "a".

这是我的package.json

{
  "name": "xxx",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "autoprefixer-stylus": "0.10.0",
    "concurrently": "3.0.0",
    "react-scripts": "0.6.1",
    "stylus": "0.54.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "watch": "concurrently --names 'webpack, stylus' --prefix name 'npm run start' 'npm run styles:watch'",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
  }
}

这是我的MovieSingle-test.js

import React from 'react';
import ReactDOM from 'react-dom';
import MoviesSingle from '../../components/movie_single/MovieSingle';

it('renders without crashing', () => {
    const div = document.createElement('div');
    ReactDOM.render(<MoviesSingle />, div);
});

那么我该如何解决这个问题,至少让通用的反应组件测试通过?

谢谢!

【问题讨论】:

    标签: reactjs jestjs create-react-app


    【解决方案1】:

    src/setupTests.js 添加到您的项目(将在运行测试之前执行):

    /**
     * fix: `matchMedia` not present, legacy browsers require a polyfill
     */
    global.matchMedia = global.matchMedia || function() {
      return {
          matches : false,
          addListener : function() {},
          removeListener: function() {}
      }
    }
    

    【讨论】:

    • 这是唯一适用于 Ionic 5 的开箱即用解决方案
    【解决方案2】:

    我也遇到了,这对我有帮助:

    here 中获取test-setup.js 并将其放到src 目录中

    window.matchMedia = window.matchMedia || function() {
        return {
            matches : false,
            addListener : function() {},
            removeListener: function() {}
        };
    };
    

    将以下内容添加到package.json

    "jest": {
        "setupFiles": ["<rootDir>\\src\\test-setup.js", "<rootDir>\\config\\polyfills.js"]
      },
    

    看看有没有帮助。

    【讨论】:

    • "jest": { "\\src\\test-setup.js", "\\config\\polyfills.js" } 不是有效的 json 格式。
    • 使用如下,同时 pollyfills 应该是第一个 =====> "setupFiles": ["\\config\\polyfills.js", "/config/testSetup .js"],
    【解决方案3】:

    添加这段代码:

    window.matchMedia =
        window.matchMedia ||
        function() {
            return {
                matches: false,
                addListener: function() {},
                removeListener: function() {}
            };
        };
    

    在 jest.setup.js 或 setupTests.js 中(您可以从 jest.config.js 中检查名称 例如。 setupFiles: ["./jest.setup.js"] )

    【讨论】:

      【解决方案4】:

      如果您使用的是 GatsbyJS,请将来自 @maow 的代码放在根目录下的 loadershim.js 文件中。

      【讨论】:

        【解决方案5】:

        这就是我设法使它工作的方法:

        // fix: `matchMedia` not present, legacy browsers require a polyfill
        global.window.matchMedia = (query) => ({
          matches: false,
          media: query,
          onchange: null,
          addListener: () => {}, // deprecated
          removeListener: () => {}, // deprecated
          addEventListener: () => {},
          removeEventListener: () => {},
          dispatchEvent: () => {},
        })
        

        【讨论】:

          【解决方案6】:

          从错误信息中找线索:

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

          这表示某些功能在测试时不可用,需要以某种方式实现才能执行操作。

          matchMedia 找到合适的polyfill 代码,例如this polyfill

          然后在src 文件夹中创建一个名为setupTests.js 的新文件并将polyfill 代码粘贴到该文件中。 React 脚本会注意该文件将在测试运行之前执行。

          现在再次运行测试。它是固定的。 Others 有同样的问题。

          【讨论】:

            【解决方案7】:

            我按照以下步骤解决了我的问题:

            • 创建了一个文件 setupTests.js
            • 将其作为 src/setupTests.js 放在 src 文件夹中
            • 将以下代码放入 setupTests.js
            window.matchMedia = window.matchMedia || function() {
                return {
                    matches: false,
                    addListener: function() {},
                    removeListener: function() {}
                };
            };
            

            注意:再次运行 npm 测试,它将解决问题(停止监视任务并重新启动它)。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2022-01-17
              • 2019-08-23
              • 1970-01-01
              • 2019-01-30
              • 2017-07-04
              • 1970-01-01
              • 2018-08-15
              • 2017-11-19
              相关资源
              最近更新 更多