I have a simple React hook:
const useHook = () => {
useEffect(() => {
window.addEventListener('click', handleClick);
}, []);
const handleClick = () => {};
return null;
};
Am I able to somehow test if the handleClick
function was called on click
event?
I can of course simulate click
event in Jest. However how to check if this fn was called?
I believe you can check the event target. If absent, then your function wasn't triggered from an event. If present, you can determine the type of event. Here I set up the listener and then call the function from code. Click the button to see the difference.
const handleClick = (e) => { if(e) { console.log(e.type); } else { console.log('called from code'); } }; document.querySelector('#clicker').addEventListener('click', handleClick); handleClick();
button { height: 20px; width: 60px; background-color: darkgrey; color: white; }
<button id='clicker'>CLICK ME</button>
How about using a count wrapper ?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.