【问题标题】:How to set or mock element scrollHeight and element clientHeight in testing?如何在测试中设置或模拟元素 scrollHeight 和元素 clientHeight?
【发布时间】:2021-09-27 06:49:00
【问题描述】:

我有一个 javascript 函数来检查是否是 html

元素,el,通过检查是一定的大小:

function isOverflow(element: string): boolean {
    const el = document.getElementById(element);
    return el.scrollHeight > el.clientHeight
}

我想测试我的功能。如何设置或模拟 scrollHeight 和 clientHeight?

it('test', () => {
   const el = document.createElement("p")
   el.setAttribute("id", "overflow")

   //How to mock these? This doesn't work "Cannot assign to 'scrollHeight' because it is a read-only property"
   el.clientHeight = 2;
   el.scrollHeight = 1;

   expect(component.isOverflow("overflow")).toBe(true);
  })

【问题讨论】:

    标签: javascript html typescript jestjs mocking


    【解决方案1】:

    由于el.clientHeight 是只读属性,我们不能设置它。我认为您可以使用高度和填充来计算el.clientHeight,如mdn blog 中所述。

    类似地,我们可以计算scrollHeight,因为它也是一个只读属性。

    scrollHeight 值等于元素需要的最小高度,以便在不使用垂直滚动条的情况下适应视口中的所有内容。高度以与 clientHeight 相同的方式测量:它包括元素的填充,但不包括其边框、边距或水平滚动条(如果存在)。它还可以包括伪元素的高度,例如 ::before 或 ::after。如果元素的内容不需要垂直滚动条就可以适应,它的scrollHeight等于clientHeight

    var para = document.createElement("P");
    para.innerHTML = "This is a paragraph.";
    
    document.getElementById("myDIV").appendChild(para);
    var el = document.getElementById("myDIV");
    el.style.padding = "10px";
    el.style.height = "100px";
    console.log(el.clientHeight)
    console.log(parseInt(el.style.padding,10) + parseInt(el.style.height,10))
    #myDIV {
    border: 1px solid  
    }
    <div id="myDIV">
    A DIV element
    </div>

    【讨论】:

      【解决方案2】:

      想通了:

      Object.defineProperty(HTMLElement.prototype, 'scrollHeight', { configurable: true, value: 500 })
      Object.defineProperty(HTMLElement.prototype, 'clientHeight', { configurable: true, value: 10 })
      

      【讨论】:

        猜你喜欢
        • 2018-05-29
        • 2019-03-19
        • 2020-04-28
        • 2017-10-13
        • 1970-01-01
        • 2021-06-16
        • 2017-01-20
        • 1970-01-01
        • 2017-04-05
        相关资源
        最近更新 更多