Monitor a function triggered by a click event

Why is my spy test always returning false? I'm attempting to spy on a function that is called during the click event of an element, but it's not working as expected.

spec:

describe('button', function() {
  before(function() {
    this.spy = sinon.spy(window, 'testMethod');
  });

  it('Should call testMethod', function() {
    $('#testBtn').click();

    expect(this.spy.called).to.equal(true);
  });
});

js:

$('#testBtn').on('click', testMethod);

function testMethod() {
  return true;
}

Answer №1

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:

  1. Execute

    $('#testBtn').on('click', testMethod);
    after you configure the spy. For example, consider placing it within your before hook.

  2. 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.

Answer №2

Experiment with

verify(this.spy).toHaveBeenInvoked();

as opposed to using

verify(this.spy.invoked).toEqual(true);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message "undefined is not a function" occurred in Protractor and the operation failed

I've searched through multiple posts but haven't been able to find a solution. HTML: <div class="col-xs-3" ng-repeat="post in posts track by $index"> <div class="well"> <h3 class="postTitle"> <a ui-s ...

Incorporate an HTTP Header into a Wicket Ajax Request

I am trying to include a custom HTTP header in all Ajax (XHR) requests made by Wicket. I attempted the following: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-My-Header', 'value'); } }); and $(doc ...

Display solely the initial row in the tbody segment of a table. Is there a method to obscure subsequent 1st rows?

The initial row of each tbody acts as the row header, containing the column names. Subsequent rows in each tbody are unnecessary and should be hidden. Classes utilized: toprowHeader = first row containing column names recordsRow = holds additional recor ...

Error: When attempting to overwrite res.render, a TypeError occurs because the property 'app' is being read from an undefined source

I am working on a project where I need to modify the behavior of the res.render method in order to consistently include an additional option, regardless of any other options present. However, when attempting to implement this modification, I encounter th ...

Retrieve the Checked Value of a Checkbox Using Ajax Post in MVC

Can anyone provide assistance? This is the code I am working with: Index.cshtml <!DOCTYPE html> <html> <head> <title>jQuery With Example</title> @Scripts.Render("~/bundles/jquery") <script type="text/javascri ...

Using jQuery to send emails

I have encountered an issue with my JavaScript code where it validates and sends an email through the Sendgrid API. Glimpse at the code below: var contact = new Vue({ el: '#form_contact', data: { company_name: null, fulln ...

How to access class type arguments within a static method in Typescript: A clever solution

An issue has arisen due to the code below "Static members cannot reference class type parameters." This problem originates from the following snippet of code abstract class Resource<T> { /* static methods */ public static list: T[] = []; ...

Stagnant state persists despite attempted update

I am facing an issue with the useState component in my property management system. The state is not updating when loading the component. I expect the state of the item to change after receiving a response in the form stepper, but when adding a new dynamic ...

How can I create a route using associations for /users/me in Sails.js?

My primary model is called Accounts. Additionally, I have several Has Many models such as Notifications and Friends Within my file named main.js, I would prefer to execute commands like: socket.get('/users/me/notifications'); instead of: soc ...

`Gradient blending in ChartJS`

Currently, I am facing an issue with my line chart having 2 datasets filled with gradients that overlap, causing a significant color change in the 'bottom' dataset. Check out my Codepen for reference: https://codepen.io/SimeriaIonut/pen/ydjdLz ...

Is it possible to add a jQuery-generated element to pure vanilla JavaScript?

I am facing a challenge in creating a new notification div when an event is triggered. Ideally, I would normally achieve this using jQuery by utilizing something like $("myDiv").append(newDiv). However, in this case, the item selector to which the new div ...

What could be causing the returned promise value to not refresh?

I am currently facing an issue with my program. Upon clicking a button, the goal is to update the "likes" attribute of a MongoDB document that has been randomly fetched. Despite setting up the logic for this, the update does not occur as intended: MongoCli ...

Issue with jQuery ajax in Internet Explorer 6

Hey there, I'm dealing with a strange issue: The success handler in my $.ajax call looks like this: function(data){ alert(data); } Seems pretty straightforward, right? The problem I'm facing is that the data sent by the server is ALW ...

How to retrieve a JSON item without knowing the name of the parent key

When requesting JSON from Wikipedia's API, the URL is: http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=WTO&prop=extracts&exsentences&explaintext&format=json This is how the response is structured: { ...

What is the best way to display a component based on a certain condition?

There are two instances where the Items component needs to be displayed. However, in one instance an additional component, Filters, is required while in another it is not. The Filters component is nested inside Items. When attempting to implement this, ...

I'm having some trouble with my jQuery.get() function in the javascript Saturday(), can anyone help me figure out what I'm doing wrong?

Can anyone help me troubleshoot my jQuery.get() method in the saturday() JavaScript function? Here is the code snippet I have been working on. This is what I have in my index.html file: <html> <head> <title>jVectorMap demo</title> ...

Experience interactive 3D model viewer in action

I want to embed this 3D model viewer into an existing div instead of creating a new one. I've made some edits to the code but it's not working. Any assistance would be greatly appreciated. <script> // Here is where the model viewer cod ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Angular JS and TypeScript - Issue: ng:areq Invalid Argument "Argument 'XXXXXX' is not a function, received undefined"

Encountering a specific error mentioned in the title. I organized models and controllers into distinct files saved under models and controllers folders respectively. Upon trying to establish a connection between them, I received an error stating "ng:areq ...