Change element size using Jest

别等时光非礼了梦想. 提交于 2019-12-23 07:27:14

问题


I have following code in my component

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

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.

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

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

and when I run test:

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

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


回答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);
    });

});


来源:https://stackoverflow.com/questions/38656541/change-element-size-using-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!