Home > Software engineering >  Test if a function was called - hooks
Test if a function was called - hooks

Time:10-23

I have a simpel react hook:

const useHook = () => {
   useEffect(() => {
      window.addEventListener('click', handleClick);
   }, []);

   const handleClick = () => {};

   return null;
};

Question: 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? Thanks!

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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`);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

1
2
3
handleClick called 3 times
  • Related