我有这个组件,测试覆盖率表明我需要测试第24和25行:
class TableToolbarComp extends Component {
state = {
shipmentId: '',
};
debouncedSetFilters = debounce(() => {
const { applyFilters } = this.props; // LINE 24
applyFilters(this.state); // LINE 25
}, 750);
updateShipmentId = ev => {
this.setState(
{
shipmentId: ev.target.value,
},
this.debouncedSetFilters,
);
};
render() {...}
}
测试:
beforeEach(() => {
applyFilters: k => k,
});
...
it('should trigger button click', () => {
const wrapper = shallow(<TableToolbarComp {...props} />);
wrapper.instance().debouncedSetFilters(750);
wrapper.instance().updateShipmentId({ target: { shipmentId: '124' } });
wrapper.instance().props.applyFilters({ shipmentId: '124' });
});
我没有收到任何错误,只是说这两行需要覆盖。
我已经尝试在测试中调用debouncedSetFilters
和applyFilters
,但是它仍然返回那两行作为未发现的内容。
我想念什么?
答案 0 :(得分:1)
没有间谍,无法有效测试功能调用。应该是:
beforeEach(() => {
applyFilters = jest.fn();
});
为了测试异步时间敏感功能,应应用计时器模拟:
jest.useFakeTimers();
const wrapper = shallow(<TableToolbarComp applyFilters={applyFilters} />);
wrapper.instance().debouncedSetFilters();
wrapper.instance().debouncedSetFilters();
expect(applyFilters).not.toHaveBeenCalled();
jest.advanceTimersByTime(750);
expect(applyFilters).toHaveBeenCalledTimes(1);
然后可以在debouncedSetFilters
测试中将updateShipmentId
存根。