我正在尝试对某个组件进行100%的测试。
这是测试:
import React from 'react';
import { shallow, mount } from 'enzyme';
import CheckboxList from '../../components/CheckboxList';
import store from '../../../../redux/store';
describe('TableToolbarComp component test', () => {
let props;
beforeEach(() => {
props = {
t: k => k,
softlayerAccountId: '232279',
columnsFilterHandler: jest.fn(() => 'columnsFilterHandler'),
setCheckboxesToCheckedHandler: jest.fn(() => 'setCheckboxesToCheckedHandler'),
checkboxes: [
{
checked: true,
value: 'itemsCancelled',
id: 'checkBoxItemsCancelled',
},
{
checked: false,
value: 'requestDate',
id: 'checkboxRequestDate',
},
],
};
});
it('should render props without errors', () => {
const wrapper = mount(<CheckboxList {...props} store={store} />);
wrapper
.find('input')
.at(0)
.simulate('change', { currentTarget: { checked: false } });
expect(
wrapper
.find('input')
.at(0)
.prop('checked'),
).toBe(false);
});
});
但是测试表明我缺少2行,即31和34:
// imports
const CheckboxList = ({
columnsFilterHandler,
setCheckboxesToCheckedHandler,
checkboxes,
t,
}) => {
const onChange = (value, id, event) => {
const item = checkboxes.slice().find(idx => idx.id === id);
if (item) {
item.checked = !item.checked;
columnsFilterHandler(value, id, event.target.value);
return { checkboxes };
}
return item; // LINE 31
};
const setCheckboxesToTrue = () => {
const items = checkboxes.filter(checkbox => checkbox.checked === false);
items.map(item => {
const newItem = item; // Created a copy of item object so eslint not yell
if (item) {
newItem.checked = !newItem.checked;
setCheckboxesToCheckedHandler(newItem.checked, newItem.id);
return { checkboxes };
}
return newItem; // LINE 44
});
};
return (
<>
<ToolbarTitle title={t('cancellations.columns')} />
<ToolbarOption>
<Button kind="ghost" small type="reset" onClick={setCheckboxesToTrue}>
{t('cancellations.resetDefault')}
</Button>
</ToolbarOption>
{checkboxes.map(checkbox => (
<ToolbarOption key={checkbox.id}>
<Checkbox
key={checkbox.id}
id={checkbox.id}
labelText={t(checkbox.labelText)}
value={checkbox.value}
checked={checkbox.checked}
onChange={onChange}
/>
</ToolbarOption>
))}
</>
);
};
CheckboxList.propTypes = {
// Props validation
};
const mapStateToProps = state => ({
checkboxes: state.cancellations.checkboxes,
});
export default compose(
connect(
mapStateToProps,
dispatch => ({
columnsFilterHandler: (value, isChecked, valueName) => {
dispatch(toggleCheckboxAction(value, isChecked, valueName));
},
setCheckboxesToCheckedHandler: (isChecked, id) => {
dispatch(setCheckboxesToChecked(isChecked, id));
},
}),
),
translate(),
)(CheckboxList);
其中一个功能是切换复选框的状态,另一个功能是将其全部设置为true。就像是重置功能。</ p>
那我该如何测试这两条线以获得100%的测试覆盖率?