Tips on utilizing Sinon for mocking a function that triggers a REST request

I'm currently navigating my way through sinon and mocha, working on the code and test provided below. My goal is to test the findAll() method without triggering an http request.

However, I've encountered an error with the current setup:

[TypeError: Cannot read property 'on' of undefined]
. I'm unsure about how to properly stub or spy the .on event.

/modles/user.js

'use strict';

const Rest = require('restler');
const Q = require('q');

class User {

  static findAll() {
    return Q.promise(function(resolve, reject) {

      Rest.get('<SOME URL FOR DATA>')
      .on('complete', function(data, response) {

        if(data instanceof Error) {
          return reject(data);
        }

        return resolve(data);
      });
    });
  }
...
}

module.exports = User;

/test/models/user.js

'use strict';

const expect = require('chai').expect;
const sinon = require('sinon');
const Rest = require('restler');

describe('User model', function() {

  var User;

  beforeEach(function() {
    this.get = sinon.stub(Rest, 'get');
  });

  afterEach(function() {
    Rest.get.restore();
  })

  it('should not blow up when requiring', function() {
     User = require('../../models/user');
     expect(User).to.not.be.undefined;
  });

  describe('findAll()', function() {
    it('should return all users', function() {

      const expected = [{personId: 1234}, {personId: 1235}];

      User.findAll()
      .then(function(result) {
        console.log('result = ', result);
      })
      .fail(function(err) {
        console.log('err = ', err);
// KEEPS DISPLAYING THIS: err =  [TypeError: Cannot read property 'on' of undefined]
      })
    });
  });

});

Answer №1

In the context previously explained, the Rest.get() function yields a result of undefined, while the findAll method necessitates it to yield an object with an on property that is of type function. By utilizing sinon, you can dictate the values that a stub will return when invoked using the stub.returns API. It is important to ensure that the callback provided to the on method is actually triggered, which can be achieved through the use of the stub.yields API. If there is a need for strict validation regarding the placement of the attached callback, one can utilize stub.callsArgWith(1, expected)

For instance:

describe('findAll()', function() {
  it('should retrieve all users', function() {
    const expected = [{personId: 1234}, {personId: 1235}];
    Rest.get.returns({
      on: sinon.stub().yields([expected])
    });
    User.findAll()
    .then(function(result) {
      console.log('result = ', result);
    });
  });
});

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

Is Meteor.js the solution for time-triggered server requests?

We are currently in the process of developing an application that matches users from a database every Wednesday and Friday. How can we achieve this using Meteor? In the server code, I am considering organizing this functionality within a timedserver.js fi ...

The process of transferring ViewBag value as a parameter in an AngularJS function

I'm facing an issue where the viewbag value is not being passed as a parameter in ng-init. Can someone guide me on how I can successfully pass the viewbag value as a parameter? angular.js { $scope.detail = function (Id) { ...

Issue encountered during Firebase deployment: Module '@babel/runtime/helpers/builtin/interopRequireDefault' not found

Struggling to deploy firebase functions and encountering multiple issues. During the deployment process, facing a babel error: Error: Cannot find module '@babel/runtime/helpers/builtin/interopRequireDefault' at Function.Module._resolveFilen ...

Mastering the art of concurrent Ajax requests using jQuery for an advanced Posting and Commenting system

In my Asp.net MVC project, I have successfully implemented a post and comment mechanism. The posts and comments are stored in different tables in the database. Additionally, using Ajax requests with jQuery, I can retrieve comments from the database and dis ...

Accessing the locally stored data and displaying it in ng-bind

My journey to learn javascript through this project has hit a roadblock. I have stored an exchange rate in local storage: localStorage.gbpUSD = "1.42746"; Now, I want to utilize it instead of the hardcoded exchange rate in the code below... <input t ...

Vuex is throwing a mysterious ReferenceError that is leaving developers

Currently, I am developing a Single Page Application (SPA) using Vue.js and Vuex. Within this project, I have set up some data in the store and displayed it in a child component. This child component includes radio buttons that trigger a function called ge ...

The filtering function stops working after the initial use

As I develop an app using React and Redux, my goal for the following code snippet is to function as a reducer within the main application. I have imported a filterData function, which works seamlessly the first time any Action type is selected. However, it ...

Issues with testing incorporating jest, react, webpack, and SVG

I recently delved into the world of React development, but I've hit a snag when trying to run a test with an SVG file. You can find the code in my GitHub repository https://github.com/alejomongua/react-playground. Upon running npm run test, I encoun ...

Creating a WordPress post popup using Ajax with SimpleModal and jQuery

I tried to follow the instructions provided in this tutorial but unfortunately, I couldn't get it to work. This is the process I followed: 1 / Including in the header <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ...

Is it possible to emphasize a duration of 25 minutes on an analog clock by utilizing CSS gradients?

I am in the process of incorporating a countdown timer but with an analog clock rather than a digital one. My objective is to emphasize the next 25 minutes as a circle sector that commences from the minute hand on the clock. Here is what I have developed ...

Once the div content is reloaded using AJAX, the refreshed HTML suddenly vanishes

My JS code reloads the div every 2 seconds: var auto_refresh = setInterval(function() { $('#indexRefresh').load('/includes/index_refresh_include.php?_=' + Math.random()); }, 2000); After that, I have an AJAX request that loads mor ...

modify input type in Reactjs based on boolean state dynamically

I am currently working on implementing a checkbox feature that allows users to toggle between viewing their password or keeping it hidden. I decided to use Material UI React for the user interface elements. The checkbox is set up and functioning properly. ...

Having trouble with the ng-class syntax?

I've been diving into the world of Angular.js and came across this code snippet: <button ng-class="{'btn pull-left', duplicatesInList === true ? 'btn-warning': 'btn-success'}" id="saveScoreButton" type="button" ng-c ...

Invoke a PHP function by utilizing a JavaScript AJAX post call

I have been exploring various topics extensively, but I have not been able to find a solution. My objective is to create an HTML hyperlink that triggers a Javascript AJAX post request on a PHP page to execute a PHP function (potentially with any number of ...

Ways to set the input=text field as read-only in JSP when receiving information from the backend

For a project I am working on, I need to implement a feature where users can view and edit their personal details on a JSP page. If a user is logged in, their information should be fetched from the session and displayed automatically. However, even if they ...

Is it possible to establish a delay for requestAnimationFrame()?

My webpage has a very long layout with text in one column and a floating element in another. I want the floating element to follow the scroll of the window and return to its original offset once scrolling stops. The current code I have is: var ticking = ...

Sending data from a child component to its parent counterpart

A component called cartComponent has a data property named cartCount which increases every time a new item is added to the cart. I want to utilize this value to update another value in the template that is not part of the component. Is it achievable? Bel ...

I am currently running a recursive loop to fetch data from MongoDB. However, the Express.js function runs through the entire script before the data can be successfully returned

Can someone assist me with setting up my Express route to handle the return of data from a recursive function that involves promises and fetching MongoDB data? Currently, my route is executing immediately without sending the data back to the client. The da ...

Tips for keeping data on a page up-to-date using Node.js and Express

Currently delving into the world of Node.js and Express, I am immersed in a project that involves pinging websites and exhibiting the results on a web page. Leveraging HoganJS for templating as well. My primary focus is to decipher the steps necessary to m ...

Options for HTML technologies in an application designed for managing enterprise metadata

Challenge We are facing the decision of determining which technologies to adopt as we transition from a rich client Silverlight application to an HTML-based client that can accommodate a metadata driven approach. Situation Our enterprise has been using ...