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

如何用Jest和Enzyme测试子组件函数属性以实现代码覆盖

Testing the Conditional CSS Class in Your Label Component

Got it, let's fix that coverage gap! The issue here is that your test suite isn't hitting both branches of the ternary condition that sets cssClass. To cover that line fully, you need to write two test cases—one for when the text is shorter than 5 characters, and another for when it's 5 or longer.

Assuming you're using React Testing Library (the standard for React component tests), here's how you can structure your tests:

import { render, screen } from '@testing-library/react';
import Label from './Label'; // Adjust the import path as needed

describe('Label Component', () => {
  test('applies "one-class" when labelText is shorter than 5 characters', () => {
    // Render the component with a short text (3 characters)
    render(
      <Label 
        labelText="Hi!" 
        renderText={(text) => { 
          const cssClass = text.length < 5 ? 'one-class' : 'other-class'; 
          return <b className={cssClass}>{text}</b>; 
        }} 
      />
    );

    // Find the bold element and check its class
    const boldElement = screen.getByText('Hi!');
    expect(boldElement).toHaveClass('one-class');
  });

  test('applies "other-class" when labelText is 5 characters or longer', () => {
    // Render the component with a longer text (5 characters)
    render(
      <Label 
        labelText="Hello" 
        renderText={(text) => { 
          const cssClass = text.length < 5 ? 'one-class' : 'other-class'; 
          return <b className={cssClass}>{text}</b>; 
        }} 
      />
    );

    // Find the bold element and check its class
    const boldElement = screen.getByText('Hello');
    expect(boldElement).toHaveClass('other-class');
  });
});

Why this works:

  • The first test triggers the text.length <5 branch (since "Hi!" is 3 characters), so the line setting cssClass to 'one-class' is executed.
  • The second test triggers the else branch (since "Hello" is 5 characters), covering the 'other-class' path.

After running these tests, your Jest coverage report should show that line as fully covered—both branches of the ternary are now being tested.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:20:53