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

Svelte组件{#if}语句单元测试未覆盖问题求解

解决Svelte组件{#if value}分支覆盖率问题

问题原因

你当前的测试用例虽然覆盖了value从无到有再到空的流程,但没有明确触发并验证{#if value}条件判断的两个完整分支(条件为真/为假),导致覆盖率工具判定分支未覆盖。具体来说,初始渲染时value为undefined(假值)、清空后为''(假值),但测试中仅通过检查特定文本是否存在来间接验证,没有明确针对{#if}分支的执行路径做验证。

修改后的测试用例

更新Example.test.js,明确覆盖{#if value}的真假分支:

import Example from './Example.svelte'
import { describe, test, expect } from '@jest/globals'
import { render, fireEvent, screen } from '@testing-library/svelte'

describe('Example.svelte', () => {
  test('正确渲染value的显示与隐藏', async () => {
    // 1. 初始渲染:value为undefined(假值),{#if}分支不执行
    const { container } = render(Example)
    const textarea = container.querySelector('textarea')
    // 验证{#if}分支的内容不存在
    expect(screen.queryByText(/./)).toBeFalsy()

    // 2. 设置value为真值,触发{#if}分支执行
    const testValue = 'hello world'
    await fireEvent.input(textarea, { target: { value: testValue } })
    expect(screen.getByText(testValue)).toBeInTheDocument()

    // 3. 设置value为空字符串(假值),{#if}分支停止执行
    await fireEvent.input(textarea, { target: { value: '' } })
    expect(screen.queryByText(testValue)).toBeFalsy()
    // 再次验证{#if}分支的内容完全不存在
    expect(screen.queryByText(/./)).toBeFalsy()
  })

  // 可选:额外测试其他假值场景(如null),确保分支覆盖全面
  test('value为null时不渲染内容', async () => {
    const { component } = render(Example)
    // 直接设置组件内部的value为null
    component.$set({ value: null })
    expect(screen.queryByText(/./)).toBeFalsy()
  })
})

修改说明

  • 初始渲染后,用screen.queryByText(/./)验证页面中没有任何文本内容(对应{#if}分支不执行的场景)。
  • 设置真值后,验证文本正确渲染(对应{#if}分支执行的场景)。
  • 清空value后,再次验证文本消失,确保分支切换正确。
  • 可选的额外测试覆盖了value为null的假值场景,进一步确保分支覆盖全面。

测试结果

修改后重新执行测试,{#if value}的分支将被完全覆盖:

PASS  src/Example.test.js
  Example.svelte
    ✓ 正确渲染value的显示与隐藏 (32 ms)
    ✓ value为null时不渲染内容 (10 ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |     100 |      100 |     100 |     100 |                    
 Example.svelte |     100 |      100 |     100 |     100 |                    
----------------|---------|----------|---------|---------|-------------------
Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.24 s

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:15:38