Reaction Ref;s Offsethe Right,即使在加载内容之后,JEST测试用例也始终返回 [英] React Ref's offsetheight, always returns '0' for jest test case even after the content is loaded

查看:0
本文介绍了Reaction Ref;s Offsethe Right,即使在加载内容之后,JEST测试用例也始终返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是反应测试库jest。在Componentdidupdate中,即使在加载内容后,仍尝试将‘this.testRef.current.offsetHeight’,获取OffsetHeight为0。我需要DOM的精确OffsetHeight,因为它有一些基于它的条件。

在反应测试库和JEST中是否有解决方案。

我正在使用DangerouslySetInnerHTML为testRef的元素绑定html内容。

推荐答案

您可以这样做:

  const originalOffsetHeight = Object.getOwnPropertyDescriptor(
    HTMLElement.prototype,
    'offsetHeight'
  );
  const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
  beforeAll(() => {
    Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
      configurable: true,
      value: 200,
    });
    Object.defineProperty(HTMLElement.prototype, 'offsetWidth', { 
      configurable: true, value: 200 
    });
  });

  afterAll(() => {
    Object.defineProperty(HTMLElement.prototype, 'offsetHeight', originalOffsetHeight);
    Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
  });

这篇关于Reaction Ref;s Offsethe Right,即使在加载内容之后,JEST测试用例也始终返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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