如何用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 <5branch (since "Hi!" is 3 characters), so the line settingcssClassto '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
相关产品推荐
相关产品推荐

