【问题标题】:Change element size using Jest使用 Jest 更改元素大小
【发布时间】:2016-12-04 00:52:47
【问题描述】:

我的组件中有以下代码

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 }

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

【问题讨论】:

    标签: reactjs jestjs reactjs-testutils


    【解决方案1】:

    我的解决方案是模拟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);
        });
    
    });

    【讨论】:

    • 感谢您的回答。只是想知道,“元素”是从哪里来的?
    • @WayneChiu AFAIK,jest 使用 jsdom 来模拟 DOM 类(例如 Element 等)-github.com/tmpvar/jsdom
    • 注:如果您有多个具有 getBoundingClientRect 特定情况的描述,则需要为该特定描述再次设置此模拟,因为全局对象原型正在发生变化
    【解决方案2】:

    不要忘记将getBoundingClientRect 的原始值放回去,因为更改它可能会影响其他测试。

    另外,在beforeEach 不需要这样做:beforeAll 可以。

    describe("Mock `getBoundingClientRect`", () => {
      let boundingClientRect;
    
      const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect;
    
      beforeAll(() => {
        Element.prototype.getBoundingClientRect = () => boundingClientRect;
      });
    
      afterAll(() => {
        Element.prototype.getBoundingClientRect = originalGetBoundingClientRect;
      });
    
      it("should mock `getBoundingClientRect`", () => {
        const element = document.createElement("div");
        boundingClientRect = new DOMRect(0, 0, 120, 120);
        const rect = element.getBoundingClientRect();
        expect(rect.width).toEqual(120);
      });
    });
    
    
    

    我的想法来自this answer

    【讨论】:

      猜你喜欢
      • 2018-12-04
      • 2018-02-02
      • 2016-04-06
      • 2017-08-31
      • 2012-05-08
      • 1970-01-01
      • 2016-05-25
      • 2020-06-25
      • 2014-10-30
      相关资源
      最近更新 更多