使用 JSDom 在节点测试环境中正确接近“窗口”

Approaching "window" correctly in Node test environment with JSDom

本文关键字:接近 窗口 JSDom 节点 测试环境 使用      更新时间:2023-09-26

我正在使用磁带和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";
我的

问题是,我该如何解决这个问题,以及我是否可以以不同的方式处理我的测试设置以避免将来发生这种情况?

测试设置不应将窗口属性粘贴到全局中。 JSDOM 理论上可以处理这种情况 - 如果您正确使用它:

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