Sinon experiences delays during an AJAX call

I am working with Mocha Chai and Sinon to test a revealing module pattern and encountering a timeout failure. How can I effectively test a method that assigns variables from an AJAX request?

Test.js

(function () {
  'use strict';

  describe('Employee Module', function() {
    var server,
        employeeJSON = {
          "employeeTemplate" : [
            {
              "userId": 1
            }
          ]
        };

    before(function () {
      server = sinon.fakeServer.create();
      server.respondWith(
        "GET",
        "/employees.json",
        [200, { "Content-Type": "application/json" }, JSON.stringify(employeeJSON)]
      );
    });

    after(function () {
      server.restore();
    });

    it('should get Employee by ID', function(done) {

      var employee = new Employee(),
          employeeData;

      employee.getData(1).done( function (data) {
        employeeData = data.employeeTemplate[0];
        assert.equal(employeeData.userId, 1, 'Employee ID equals 1');
        done();
      });
    });
  });
})();

Employee.js

var Employee = function() {

  var EmployeeInfo = {};

  var loadUserinfo = function(userid) {
    return $.ajax({
      type: 'GET',
      data:{userid: userid},
      url: '/employees.json',
      dataType: 'json',
      async: true,
      success: function(data) {
        return data;
      }
    });
  };

  var getData = function (userid) {
    return loadUserinfo(userid).done();
  };

  return {
    getData: getData
  };

};

Answer №1

In order to proceed with your test, it is important to instruct FakeServer on when to respond. The FakeServer API documentation can be consulted for guidance.

Here is an example illustrating this concept:

it('should retrieve Employee by ID', function(done) {

  var employee = new Employee(),
      employeeData;

  employee.getData(1).done( function (data) {
    employeeData = data.employeeTemplate[0];
    assert.equal(employeeData.userId, 1, 'Employee ID equals 1');
    done();
  });

  server.respond(); // Requesting a response from sinon to proceed with the test
});

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

When attempting to make an AJAX call using the console, an error was encountered stating that the function $.ajax is not available

Currently experimenting with an ajax call from my console to a local server, but encountering an error: VM4460:1 Uncaught TypeError: $.ajax is not a function(…) Here's the code snippet causing the issue: url = 'http://localhost:8080/testform ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

Is it feasible to arrange <DIV>s based on their dates?

I encountered an issue while working with an ordering function. var $wrapper = $('#list'); $wrapper.find('.blogboxes').sort(function (a, b) { return +b.dataset.date - +a.dataset.date; }) .appendTo( $wrapper ); <script src="ht ...

What is the reason for AngularJS not utilizing the most recently assigned value?

<html> <head> <title>Test</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="angul ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

Using Polymer in Chrome Extension content script

Currently, I am experimenting with incorporating Polymer into a chrome extension. My main objective is to take advantage of styling encapsulation in order for my content scripts to operate independently from the CSS on the visited webpage. To begin, I hav ...

What is the maximum number of JSON responses that can be handled by AJAX?

Upon entering the site, I am attempting to receive a JSON as an AJAX response. However, I am curious if there is a limit to the size of the object I can retrieve - whether through a GET or POST request? $http({ method: 'POST', url: &apos ...

Tips for setting a threshold in a highcharts ng chart

I am struggling with setting the threshold to zero on a simple line chart using Highchart ng. According to the Highcharts API, the property should be plotOptions.series.threshold. However, despite following advice from this source, I can't seem to get ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

What could be causing Wordpress Jquery to only function properly after a page refresh?

Here is the code snippet I am working with: <script type="text/javascript"> jQuery( document ).ready(function() { jQuery('#bookbtn_loc_1').on('click', function(event){ jQuery("a.da-close").click(); ...

Vue- async function results in a Promise object with a status of <pending>

Hey everyone, I could use some assistance with my Vue code. Here's the issue: I'm attempting to retrieve data (specifically anime) from an online anime API. In my project, I have two files: Anime.vue (the view page) and getAnime.js (which house ...

The fade-in effect will initiate from the start once the mouse leaves the element (with a

Currently, I am in search of a solution for improving the navigation menu I am developing. By clicking on this JSFiddle link, you can view the code in action. The issue I am facing is that the fadeIn effect should only occur when hovering over the nav-ite ...

I am currently having trouble with req.query not functioning correctly within Next.js for reading query parameters

I am facing an issue while working with a REST API in Next.js 13. I have created the API, which can be accessed at http://localhost:3000/api/portfolio. However, when I try to filter the data using query parameters like http://localhost:3000/api/portfolio?s ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

ajax fails to return a valid request due to an undefined index

I am encountering an issue with my simple AJAX request <script> $(document).ready(function() { setInterval(() => { var val1 = $("#id").val(); var val2 = $("#dt").val(); $.ajax({ ...

I keep getting redirected to a blank page by JS

I've created a JavaScript script that smoothly fades in the page when a user enters it and fades out when they click a link to another page. The script is working as intended, but I'm facing an issue with anchor links on the page. Whenever I clic ...

Arrange items in a particular order

I need help sorting the object below by name. The desired order is 1)balloon 2)term 3)instalment. loanAdjustmentList = [ { "description": "Restructure Option", "name": "instalment", " ...

Retrieve a JSON object from a JSON array using a specific key

I am facing a situation where I have a json array containing multiple json objects. Let's take the example of a course object with the following structure: {"name": "Math", "unit": "3"} The json array looks something like this: [{"name": "Math", "u ...

AngularJS fails to prioritize the following element

Here is my HTML code: <div ng-app="app"> <form> <div class="form-group"> <label >Username</label> <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/> ...