Eri*_*ric 2 undefined node.js typescript reactjs jestjs
玩笑配置:\ntestEnvironment:\'jsdom\'
\n示例代码:
\nit(\'test\', async () => {\n await act(async () => {\n await asyncRender(\n <Popover isOpen position={new DOMRect(10, 10)}>\n <Button text="Child Button" />\n </Popover>\n );\n });\n\n expect(...);\n});\nRun Code Online (Sandbox Code Playgroud)\n获取错误信息\xef\xbc\x8c ReferenceError: DOMRect is not defined。
有人对这个问题有什么建议吗?
\n小智 6
问题是 jsdom 没有实现 DOMRect 类。如果您检查源代码,您会发现它通过返回具有 DOMRect 等属性的普通对象来实现 getClientBoundingRect。但到处都没有课。
解决方案是
A) 在 jsdom repo 上打开一个问题并希望他们添加它
B)完全不使用 DOMRect 来解决这个问题:在您的示例中,传递 {x:10,y:10} 对象可能会正常工作
C) 在 jest 环境中创建自定义 DOMRect 类。有(据说)多种方法可以做到这一点。对我(jest 27+)有用的是创建一个提供 jsdom 环境 + 自定义 DOMRect 模拟的文件:
const JsDomEnv = require('jest-environment-jsdom');
class CustomEnvironment extends JsDomEnv {
async setup() {
await super.setup();
this.global.DOMRect = class DOMRect {
bottom:number=0;
left:number=0;
right:number=0;
top:number=0;
constructor (public x=0, public y=0, public width=0, public height=0) {};
static fromRect(other?: DOMRectInit): DOMRect {
return new DOMRect(other.x,other.y,other.width,other.height)
}
toJSON() {
return JSON.stringify(this)
}
}
}
}
module.exports = CustomEnvironment;
Run Code Online (Sandbox Code Playgroud)
然后将文件路径传递给 jest config:testEnvironment:'./custom-env.ts' 而不是 'jsdom'。