使用Jest更改元素大小

格列布

我的组件中有以下代码

var rect = ReactDOM.findDOMNode(this).getBoundingClientRect();

我使用d3js并在组件中渲染图。但是当我运行测试时,有任何svg标签。我认为这是因为所有rect字段都等于0。

这是浏览器中console.log(rect)的输出

ClientRect {顶部:89,右侧:808,底部:689,左侧:8,宽度:800…}

当我运行测试时:

{底部:0,高度:0,左侧:0,右侧:0,顶部:0,宽度:0}

那么有没有办法设置元素的大小?

阿伦约夫

我的解决方案是模拟getBoundingClientRect(我目前正在使用jest 16.0.1)

describe('Mock `getBoundingClientRect`', () => {
    beforeEach(() => {
        Element.prototype.getBoundingClientRect = jest.fn(() => {
            return {
                width: 120,
                height: 120,
                top: 0,
                left: 0,
                bottom: 0,
                right: 0,
            }
        });
    });
    it('should mock `getBoundingClientRect`', () => {
        const element = document.createElement('span');
        const rect = element.getBoundingClientRect();
        expect(rect.width).toEqual(120);
    });

});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章