使用 nodejs 进行测试时,svgElement.getBoundingClientRect() 始终返回零

Ste*_*fan 2 javascript testing node.js jestjs

我创建了一些 svg 元素并想确定它的大小

svgElement.getBoundingClientRect()
Run Code Online (Sandbox Code Playgroud)

如果 svgElement 附加到文档中,我的代码就可以工作

document.body.appendChild(svgElement)
Run Code Online (Sandbox Code Playgroud)

如果我在浏览器(谷歌浏览器)中运行代码

然而,在使用nodejs和 jest 进行测试时,生成的边界矩形的宽度和高度始终为零。

=>如何使用nodejs正确运行代码?

Ste*_*fan 6

Nodejs 使用 jsdom,并且getBoundingClientRect仅实现返回正确的属性,而不返回正确的值。

另请参阅https://github.com/jsdom/jsdom/issues/653

对于测试,getBoundingClientRect应该模拟该方法,例如:

spyOn(svgElement,'getBoundingClientRect').and.returnValue({
    width: 10,
    height: 10,
    top: 0,
    left: 0,
    right: 10,
    bottom: 10
});
Run Code Online (Sandbox Code Playgroud)