You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vitest测试中如何设置并读取div高度以验证useVerticalOverflow函数

解决Vitest中getBoundingClientRect返回高度为0的问题

在Vitest(基于jsdom环境)中,未挂载到DOM或未触发布局计算的元素,getBoundingClientRect()会返回全0的矩形——这是因为jsdom不会自动执行浏览器的布局渲染流程。针对你的useVerticalOverflow函数测试,按以下步骤修正即可:

  • 必须将测试元素挂载到document.body
    未加入DOM树的元素,jsdom不会计算其布局尺寸。创建测试div后,一定要执行document.body.appendChild(div),测试完成后记得清理DOM避免污染。

  • 显式设置元素的盒模型与内容
    仅设置height可能不够,要确保元素display不为none(div默认是block,无需额外设置),如果用到padding/border,建议加上box-sizing: border-box避免尺寸计算偏差。同时要填充足够触发溢出的内容:

    const testDiv = document.createElement('div')
    testDiv.style.height = '200px'
    testDiv.style.overflow = 'hidden'
    testDiv.style.boxSizing = 'border-box'
    // 填充足够长的内容触发溢出
    testDiv.innerHTML = Array(100).fill('<p>测试内容行</p>').join('')
    document.body.appendChild(testDiv)
    
  • 手动触发布局计算
    jsdom需要强制触发布局才能更新getBoundingClientRect的值,最简单的方式是访问元素的offsetHeight或scrollHeight属性,这会迫使jsdom计算布局:

    // 触发布局计算
    void testDiv.offsetHeight
    
  • 完整测试用例示例
    针对useVerticalOverflow的测试可以这么写:

    import { describe, it, expect, afterEach } from 'vitest'
    import { useVerticalOverflow } from '@/composables/useVerticalOverflow'
    
    describe('useVerticalOverflow', () => {
      afterEach(() => {
        // 测试后清空DOM
        document.body.innerHTML = ''
      })
    
      it('检测到垂直溢出', () => {
        const testDiv = document.createElement('div')
        testDiv.style.height = '200px'
        testDiv.style.overflow = 'hidden'
        testDiv.innerHTML = Array(100).fill('<p>测试行</p>').join('')
        document.body.appendChild(testDiv)
    
        // 强制触发布局
        void testDiv.offsetHeight
    
        const { isOverflowing, difference } = useVerticalOverflow(testDiv)
        expect(isOverflowing).toBe(true)
        expect(difference).toBeGreaterThan(0)
      })
    
      it('内容未溢出时返回正确状态', () => {
        const testDiv = document.createElement('div')
        testDiv.style.height = '200px'
        testDiv.innerHTML = '<p>仅一行测试内容</p>'
        document.body.appendChild(testDiv)
    
        void testDiv.offsetHeight
    
        const { isOverflowing, difference } = useVerticalOverflow(testDiv)
        expect(isOverflowing).toBe(false)
        expect(difference).toBe(0)
      })
    })
    
  • 额外提示
    如果你的函数依赖window.innerHeight,可以用vi.stubGlobal('innerHeight', 800)在测试中模拟窗口高度,避免受jsdom默认值影响。

内容的提问来源于stack exchange,提问作者qqq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 07:52:48