[英]How can I test a debounce function with Jest/Enzyme?
我有這個組件,其中測試覆蓋率說我需要測試第 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' });
});
而且我沒有收到任何錯誤,它只是說那 2 行需要覆蓋。
我已經試圖叫debouncedSetFilters
和applyFilters
的測試,但它仍然返回那些2線為揭開。
我錯過了什么?
沒有間諜就無法有效地測試函數調用。 它應該是:
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
測試中存根。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.