在JSDom的Nodetesting环境中正确接近“窗口”

我使用Tape和JSDomtesting了我的React应用程序,在每个testingJS文件的顶部导入了以下模块:

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' 

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

  SVGPathSeg.prototype.classname = "SVGPathSeg"; ^ ReferenceError: SVGPathSeg is not defined 

其中,如果我去错误的来源(填充),我看到:

 (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"; 

我的问题是,我该如何解决这个问题呢?另外,为了避免这种情况,我可以以不同的方式处理testing设置吗?

您的testing设置不应该将窗口属性粘贴到全局中。 jsdom理论上可以处理这种情况 – 如果你正确使用它:

你应该为jsdom提供一个完整的testing包,就像你在浏览器中testing一样。 这通常意味着您必须浏览您的testing,然后将最终的脚本文件提供给jsdom(就像在普通浏览器中那样)。 另请参阅此练习的评论/主题。