【问题标题】:jest js: wicg-inert included cannot redefine property inertjest js:包含的 wiCG-inert 无法重新定义属性 inert
【发布时间】:2019-07-15 20:30:32
【问题描述】:

我正在尝试在 React Modal 中进行简单的单元测试。如果它在没有道具的情况下安装。这是 test.js 文件。

import React from "react";
import { mount } from "enzyme";
import MyModal from ".";
import "wicg-inert";
import "animate.css";

describe("MyModal component", () => {
  describe("When props is missing", () => {
    it("should be defined", () => {
      expect(() => mount(<MyModal />)).toBeDefined();
    });
  });
});

错误信息:

Test suite failed to run

TypeError: Cannot redefine property: inert
    at Function.defineProperty (<anonymous>)

  4 | import classnames from "classnames";
  5 | import MyButton, { MyButtonGroup } from "components/MyButton";
> 6 | import "wicg-inert";
  7 | import "animate.css";
  8 |
  9 | import "./MyModal.scss";

  at node_modules/wicg-inert/dist/inert.js:794:10
  at node_modules/wicg-inert/dist/inert.js:2:66
  at Object.<anonymous> (node_modules/wicg-inert/dist/inert.js:5:2)
  at Object.<anonymous> (src/components/MyModal/MyModal.jsx:6:1)
  at Object.<anonymous> (src/components/MyModal/index.mjs:1:318)
  at Object.<anonymous> (src/components/MyModal/MyModal.test.js:3:32)

在节点模块内的 inert.js 文件中。第一行是 792。

 var inertManager = new InertManager(document);

 Object.defineProperty(Element.prototype, 'inert', {
    enumerable: true,
    get: function get() {
       return this.hasAttribute('inert');
    },
    set: function set(inert) {
       inertManager.setInert(this, inert);
    }
 });

完全不知道如何解决,找不到任何解释。

【问题讨论】:

  • wicg-inert 设计为只在页面上运行一次,并且在导入后立即运行。我的猜测是它在您的代码中的某个地方被导入,所以当它在您的测试顶部再次导入时,它会导致错误。
  • 如果我删除行“import”wigg-inert";" rfom .test.js,测试只在第一次运行,第二次运行失败,所以是缓存问题。

标签: javascript reactjs jestjs enzyme


【解决方案1】:

package.json 中添加以下内容:

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-scripts test --env=jsdom --silent **--no-cache**",
    "eject": "react-scripts eject",
    "doc": "jsdoc -R src/README.md src/ -r -d doc/"
  },

test.js 中删除该行:

import "wicg-inert";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2019-07-26
    • 2020-05-12
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多