使用Jest更改元素大小 [英] Change element size using Jest

查看:503
本文介绍了使用Jest更改元素大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件中包含以下代码

I have following code in my component

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

我使用 d3js 并在组件中呈现图形.但是,当我运行测试时,有任何 svg 标签.我认为发生这种情况是因为所有 rect的字段都等于0.

I use d3js and render graph in the component. But when I run test there are any svg tags. I assume that it happens because all rect's fields equals 0.

此处在浏览器中为 console.log(rect)输出:

Here is output for console.log(rect) in browser:

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

ClientRect {top: 89, right: 808, bottom: 689, left: 8, width: 800…}

当我运行测试时:

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

{ bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 }

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

So is there a way to set size of the element?

推荐答案

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

My solution is to mock getBoundingClientRect (I'm currently using 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);
    });

});

这篇关于使用Jest更改元素大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆