新增动态列后Testing-Library测试用例失败,求解决方法
表格组件测试用例新增单选框列后失败的解决方法
问题描述
我是testing-library新手,之前表格组件的测试用例都能正常通过,但在根据mode动态添加单选框/复选框列后,测试用例失败。注释掉以下新增代码后测试恢复正常,请问该如何修改以通过测试?
新增的单选框代码片段
<td> <input class="input-selection" type="radio" /> </td>
失败的断言
expect(container.firstChild).toMatchSnapshot();
测试代码
import React from 'react'; import Table from './Table'; import { render, cleanup, fireEvent } from '@testing-library/react'; describe('<Table/>', () => { const headerLabels = [ 'Claim Number', 'Date of Admission', 'Date of Discharge', 'Clinic/Hospital' ]; const dataRows = [ ['test-id', '12-03-2021', '26-03-2021', 'PARKWAY EAST'], ['CBGDC21000386-00', '13-03-2021', '25-03-2021', 'RESTRUCTURED HOSPITAL'], ['CBGDC21000386-00', '14-03-2021', '24-03-2021', 'PARKWAY EAST'], ['CBGDC21000386-00', '15-03-2021', '23-03-2021', 'SUNWAY'], ['CBGDC21000386-00', '16-03-2021', '22-03-2021', 'KEPPAL'], ['CBGDC21000386-00', '17-03-2021', '21-03-2021', 'PARKWAY EAST'], ['CBGDC21000386-00', '18-03-2021', '20-03-2021', 'PARKWAY EAST'] ]; afterEach(cleanup); it('Should render basic component', () => { const { container } = render( <Table headerLabels={headerLabels} dataRows={dataRows} mode="single" title="test title" /> ); expect(container.firstChild).toMatchSnapshot(); }); it('should invoke onChange callback', () => { const onChange = jest.fn(); const { getByText } = render( <Table headerLabels={headerLabels} dataRows={dataRows} mode="single" title="test title" onChange={onChange} /> ); fireEvent.click(getByText('test-id')); expect(onChange).toHaveBeenCalled(); }); });
解决步骤
1. 更新快照文件
快照测试的核心是对比当前渲染结果和已存储的快照。新增单选框列后,组件结构发生变化,旧快照已不匹配,需要更新快照:
- 运行测试时加上
--updateSnapshot(或短写-u)参数:npm test -- -u或yarn test -u - 这会让Jest生成新的快照,后续测试将基于新的组件结构进行对比。
2. 完善单选框属性(可选但推荐)
为了测试稳定性和符合HTML规范,给单选框补充必要属性:
- 添加
name属性:确保同一组单选框的name一致,避免无标识元素干扰测试 - 添加
value属性:绑定行数据的唯一标识,方便后续测试选中状态
修改后的示例代码:
<td> <input class="input-selection" type="radio" name="claim-selection" value={rowId} /> </td>
3. 补充单选框相关测试用例(可选)
既然新增了交互元素,建议补充对应的测试覆盖:
it('should render radio buttons in single mode', () => { const { getAllByRole } = render( <Table headerLabels={headerLabels} dataRows={dataRows} mode="single" title="test title" /> ); // 验证单选框数量与数据行数一致 const radioButtons = getAllByRole('radio'); expect(radioButtons).toHaveLength(dataRows.length); }); it('should trigger onChange when radio button is clicked', () => { const onChange = jest.fn(); const { getAllByRole } = render( <Table headerLabels={headerLabels} dataRows={dataRows} mode="single" title="test title" onChange={onChange} /> ); fireEvent.click(getAllByRole('radio')[0]); expect(onChange).toHaveBeenCalled(); });
内容的提问来源于stack exchange,提问作者Alex Aung
相关产品推荐
相关产品推荐

