我有一个简单的React钩子:
const useHook = () => {
useEffect(() => {
window.addEventListener('click', handleClick);
}, []);
const handleClick = () => {};
return null;
};
我是否能够以某种方式测试handleClick
函数是否在click
事件上被调用?
click
事件。然而,如何检查这个fn是否被调用?使用计数包装器如何?
function countFn(fn) {
let wrapper = function() {
wrapper.called ++;
return fn.apply(this, arguments);
}
wrapper.called = 0;
return wrapper;
}
const handleClick = countFn((e) => {console.log(e)});
handleClick(1);
handleClick(2);
handleClick(3);
console.log(`handleClick called ${handleClick.called} times`);
1
2
3
handleClick called 3 times