如何用Jest/Enzyme测试React组件含双方法的onClick事件以实现全覆盖率
How to Test the onClick Event in Your Normalize React Component for Full Coverage
Hey there! Let's get that missing test coverage sorted out. First, let's break down why the button isn't showing up in your current test—your baseProps have values that hide it. The button only renders when three conditions are met:
newResponseis false (sincethis.props.newResponse ? null : ...)datasourceCatalogis null/undefined (since!this.props.datasourceCatalog ? <div id='next-button-modal'>...)THeadhas a valid value (sincethis.props.THead ? <div>...)
Here's how to update your test suite to cover the onClick logic fully:
Step 1: Create Props That Make the Button Visible
First, adjust your props to meet all the conditions for the button to render:
const buttonVisibleProps = { ...baseProps, newResponse: false, // Triggers the "Normalized Data" section datasourceCatalog: null, // Shows the button container THead: '<tr><th>Sample Header</th></tr>', // Ensures the table section renders TBody: '<tr><td>Sample Row</td></tr>' };
Step 2: Write the Click Event Test
Add this test case to your describe block to simulate the button click and verify the props methods are called:
it('Should call toggleModal and nextTab when the "Proceed To Shape" button is clicked', () => { // Reset mock functions to avoid cross-test contamination toggleModal.mockClear(); nextTab.mockClear(); // Render the component with props that make the button visible const wrapper = shallow(<Normalize {...buttonVisibleProps} />); // Locate the button using its ID const proceedButton = wrapper.find('#next-btn-ready-modal'); // Simulate the onClick event proceedButton.simulate('click'); // Assert both props methods were called exactly once expect(toggleModal).toHaveBeenCalledTimes(1); expect(nextTab).toHaveBeenCalledTimes(1); });
Step 3: Clean Up Your Existing Test (Optional)
You can keep your original render test, but make its purpose clearer:
it('Should render correctly with initial props', () => { expect(wrapper).toMatchSnapshot(); // Or add specific render assertions });
Why This Works
- By setting
newResponse: false, we trigger the section of the render that includes the table and button container. - Setting
datasourceCatalog: nullremoves the condition that hides the button div. - Simulating the click triggers the inline onClick handler, which calls both
this.props.toggleModal()andthis.props.nextTab(). mockClear()ensures our mock functions start fresh for each test, preventing false positives from previous runs.
Quick Notes
- Since you're using Enzyme's
shallowrendering, this approach works perfectly—shallow rendering handles inline event handlers correctly. - If you ever switch to
mountfor full DOM rendering, the code will be nearly identical (just replaceshallowwithmount).
内容的提问来源于stack exchange,提问作者user 9191
相关产品推荐
相关产品推荐

