Javascript 如何使用Jest/酶测试去盎司函数?
我有一个组件,其中测试覆盖率表示我需要测试第24行和第25行:Javascript 如何使用Jest/酶测试去盎司函数?,javascript,reactjs,ecmascript-6,jestjs,enzyme,Javascript,Reactjs,Ecmascript 6,Jestjs,Enzyme,我有一个组件,其中测试覆盖率表示我需要测试第24行和第25行: class TableToolbarComp extends Component { state = { shipmentId: '', }; debouncedSetFilters = debounce(() => { const { applyFilters } = this.props; // LINE 24 applyFilters(this.state);
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' });
});
beforeach(()=>{
applyFilters:k=>k,
});
...
它('应该触发按钮点击',()=>{
常量包装器=浅();
wrapper.instance().debouncedSetFilters(750);
wrapper.instance().updateShipmentId({target:{shipmentId:'124'}});
wrapper.instance().props.applyFilters({shipmentId:'124'});
});
我没有收到任何错误,只是说这两条线需要覆盖
我已经尝试在测试中调用了debouncedSetFilters
和applyFilters
,但它仍然返回这两行代码
我遗漏了什么?没有间谍,函数调用无法有效测试。应该是:
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);
jest.useFakeTimers();
常量包装器=浅();
wrapper.instance().debouncedSetFilters();
wrapper.instance().debouncedSetFilters();
expect(applyFilter).not.tohavebeincall();
开玩笑提前计时(750);
期望(applyFilters)。已收集时间(1);
然后,
debouncedSetFilters
可以在updateShipmentId
test中存根。为什么两次调用wrapper.instance().debouncedSetFilters()
还是打字错误?这就是测试去发音功能的方法。两个调用应导致一个applyFilters调用。