【问题标题】:React Smooth DND Library causing and 'illegal invocation error'React Smooth DND Library 导致和“非法调用错误”
【发布时间】:2019-09-23 21:17:47
【问题描述】:

图书馆

  • 开玩笑
  • React 测试库

说明 当我对本身使用 smooth-dnd 的组件运行测试时。它工作正常。但是,当我运行所有测试时,我得到了这个非法调用错误。

来自 jsdom 库的 Node.js

Object.defineProperty(Node.prototype, "childNodes", {
get() {
if (!this || !module.exports.is(this)) {
  throw new TypeError("Illegal invocation"); // Error here
}

return utils.getSameObject(this, "childNodes", () => {
  return utils.tryWrapperForImpl(this[impl]["childNodes"]);
});
 },

 enumerable: true,
 configurable: true
});

这是错误。

Test suite failed to run

TypeError: Illegal invocation

  at Node.get [as childNodes] (node_modules/jsdom/lib/jsdom/living/generated/Node.js:423:13)
  at Node.get (node_modules/smooth-dnd/dist/index.js:1:11462)
  at node_modules/smooth-dnd/dist/index.js:1:11356
  at node_modules/smooth-dnd/dist/index.js:1:96
  at Object.<anonymous> (node_modules/smooth-dnd/dist/index.js:1:195)
  at node_modules/react-smooth-dnd/dist/index.js:1:145`

似乎smooth-dnd调用了jsdom,而jsdom抛出了异常。但它只发生在我运行所有测试时。当我单独运行它们时,它们运行良好。

jsdom 中的节点是干什么用的?

根据代码,这一行正在捕获错误(!this || !module.exports.is(this)

为什么 Node 在我运行所有测试时未定义,但在我单独运行测试时定义?

是否有可能的解决方案,或者我应该尝试不同的拖放库。 任何帮助将不胜感激。

【问题讨论】:

  • 请提供您用于测试的代码,以及有效的测试代码。

标签: reactjs jestjs jsdom


【解决方案1】:

对于那些(像我一样)#36 和#52 不起作用的人,我不得不花几个小时来弄清楚它。

smooth-dnd 库中,有一个 polyfill.ts 可以做到,很简单:

// Overwrites native 'firstElementChild' prototype.
// Adds Document & DocumentFragment support for IE9 & Safari.
// Returns array instead of HTMLCollection.
(function(constructor) {
    if (constructor &&
        constructor.prototype &&
        constructor.prototype.firstElementChild == null) {
        Object.defineProperty(constructor.prototype, 'firstElementChild', {
            get: function() {
                var node, nodes = this.childNodes, i = 0;
                while (node = nodes[i++]) {
                    if (node.nodeType === 1) {
                        return node;
                    }
                }
                return null;
            }
        });
    }
})(Node || Element);

而且那个 polyfill 只适用于 IE9 和 Safari 8,Chrome 版本也高达 29。因为我们使用的是 chrome 和其他版本的 v.289,所以这甚至没有用。在我的(更新的)包中,我刚刚删除了这个功能,每个 Jest 测试都可以正常工作。

我花时间以我自己的方式包装所有内容,删除 smooth-dnd 依赖项并将所有内容制作为 .js。

如果您仍在为这个问题苦苦挣扎,请通过vue-dndrop 看看我的解决方案。

如果这对你有帮助,请告诉我。 ?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2022-10-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多