The issue arises from the fact that the line causing the problem is:
$('#testBtn').on('click', testMethod);
This line captures a reference to testMethod
before the spy is established. Thus, it ends up referencing the original function instead of the spy. This renders setting a spy on window.testMethod
ineffective because the function invoked by a click event will always be the original testMethod
. To address this challenge, there are a few solutions at your disposal:
Execute
$('#testBtn').on('click', testMethod);
after you configure the spy. For example, consider placing it within your before
hook.
Modify
$('#testBtn').on('click', testMethod);
to $('#testBtn').on('click', function () { testMethod(); });
. The anonymous function will obtain a fresh reference to testMethod
each time a click event is processed. Consequently, it will acquire a reference to the spy once it has been set.
To confirm my statements, I conducted a test that replicates your scenario and applied the aforementioned fixes.