【问题标题】:Approaching "window" correctly in Node test environment with JSDom使用 JSDo 在 Node 测试环境中正确接近“窗口”
【发布时间】:2016-03-15 11:31:12
【问题描述】:

我正在使用 Tape 和 JSDom 测试我的 React 应用,并在每个测试 JS 文件的顶部导入以下模块:

import jsdom from 'jsdom'

function setupDom() {
  if (typeof document === 'undefined') {
    global.document = jsdom.jsdom('<html><body></body></html>');
    global.window = document.defaultView;
    global.navigator = window.navigator;
    global.WebSocket = function(){};
  }
}

setupDom();

但是,在我的一个 React 组件中,我像这样导入 pathseg polyfill

import 'pathseg'

但是,当我运行测试时,我收到此错误:

    SVGPathSeg.prototype.classname = "SVGPathSeg";
        ^

ReferenceError: SVGPathSeg is not defined

如果我找到错误的根源(在 polyfill 中),我会看到:

(function() { "use strict";
if (!("SVGPathSeg" in window)) {
    // Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-InterfaceSVGPathSeg
    window.SVGPathSeg = function(type, typeAsLetter, owningPathSegList) {
        this.pathSegType = type;
        this.pathSegTypeAsLetter = typeAsLetter;
        this._owningPathSegList = owningPathSegList;
    }

    SVGPathSeg.prototype.classname = "SVGPathSeg";

我的问题是,我该如何解决这个问题,另外,我能否以不同的方式处理我的测试设置以避免将来出现这种情况?

【问题讨论】:

  • 您认为总是可以在 setupDom 中通过一些脏的复制/粘贴 global.SVGPathSeg = function(... 来解决这个问题,但这不是完全放弃已弃用的 SVGPathSeg 以支持 SVG 路径数据 API 的好机会在 patheg 文档中提到?

标签: javascript node.js testing reactjs jsdom


【解决方案1】:

您的测试设置不应在全局中粘贴窗口属性。 jsdom 理论上可以处理这种情况——如果你使用正确的话:

您应该为 jsdom 提供一个完整的测试包,就像您在浏览器中进行测试一样。这通常意味着您必须浏览您的测试,然后将最终脚本文件提供给 jsdom(就像您在普通浏览器中所做的那样)。另请参阅 this 关于该实践的评论/线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多