gpt4 book ai didi

node.js - 引用错误: DOMRect is not defined

转载 作者:行者123 更新时间:2023-12-02 18:16:30 53 4
gpt4 key购买 nike

  1. Jest 配置:测试环境:'jsdom'

  2. 示例代码:

    it('test', async () => {
    await act(async () => {
    await asyncRender(
    <Popover isOpen position={new DOMRect(10, 10)}>
    <Button text="Child Button" />
    </Popover>
    );
    });

    expect(...);
    });
  3. 获取错误信息,ReferenceError: DOMRect is not Defined

有人对这个问题有什么建议吗?

最佳答案

问题是 jsdom 没有实现 DOMRect 类。如果您检查源代码,您会发现它通过返回具有 DOMRect 等属性的普通对象来实现 getClientBoundingRect。但到处都没有课。

解决方案是

A) 在 jsdom 存储库中提出问题并希望他们添加它

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;

然后将文件路径传递给 jest config:testEnvironment:'./custom-env.ts'而不是'jsdom'。

关于node.js - 引用错误: DOMRect is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71521976/

53 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com