Testing Ajax code encounters error

Currently, I am running a code test with Jasmine and setting up a mock object for the ajax method.

spyOn($,'ajax').and.callFake(function(e){
console.log("is hitting");
})

In order to test the code snippet below:

$.ajax({
               url: AppManager.defaults.contextPath + "/solutions/mcn/mcn-lookup-list",
               data: {
                    mcnNumber       : mcnNumberData,
                    mcnCustomerName : mcnCustomerNameData
               },
               dataType: "json",
               type: "GET",
               global: false
        })
        .done(function(data) {
               solution.CommonObjects.theSolution.orderHandoff.mcnSearchData = self.filterMCNSearchData(data, resultObj);
               $promise.resolve();
        })
        .fail(function() {
             $promise.reject();
             self.displayErrorPopup('MCN Search Error','There is no MCN associated with MCN Number or MCN Customer Name Entered!!!');
        });
    },

An error is being thrown: "cannot read done of undefined". Do I also need to create a spy for that? Can you please provide assistance with the code for that?

Answer №1

Code refinements needed:

  • You have correctly implemented the spying mechanism, but remember to return a promise object through your spy. In essence, your spy function should return something like this ==>
    return new $.Deferred().resolve(dummyData).promise();
  • There are various methods to create a deferred object/promise object. I recommend studying both Promise & Deferred
  • Could you please clarify the origin of your $promise? Is it a feature of require.js?

Here's a sample way to simulate ajax calls.

var testObj = {
    ajaxFunction: function() {
      $.ajax({
        url: 'https://jsonplaceholder.typicode.com/posts/1'
      }).done(function(data){
        consoleLogFunction(data);
      });
    }
};

var consoleLogFunction = function(data){
    console.log("The length of array is..=> "+ data.length);
};

describe("ajax test suite", function() {
  it("expect true to be true", function() {
    var dummyData = ["Foo", "Boo"];
    spyOn($, 'ajax').and.callFake(function(e){
      return new $.Deferred().resolve(dummyData).promise();
    });
    spyOn(window, 'consoleLogFunction').and.callThrough();
    testObj.ajaxFunction();
    expect(window.consoleLogFunction).toHaveBeenCalledWith(dummyData);
  });
});

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

Trimming Picture on User's Device

Currently, I am utilizing the jQuery ImgAreaSelect 0.9.10 plugin to crop images that are uploaded by users. The data input format being used is "multipart/form-data". Upon cropping an image with the plugin, it provides me with coordinates in pixels. Howev ...

No need for jQuery with this scrolling image gallery

I recently created a horizontal scrolling image gallery with thumbnails underneath. The goal is to click on a thumbnail and have the corresponding image scroll into view. Here's the HTML setup: <div class="images_container"> <img id="imag ...

Reorganizing JSON structures by incorporating unique identifiers into nested elements

I am working on restructuring an incoming JSON object to utilize in a React component. The JSON data that I'm receiving is stored in jsonData. This is the current structure of my code: const jsonData = { "Jonas": { "position": "CTO", "em ...

What is the process for deleting an animation using JavaScript, and how can the background color be altered?

Two issues are currently troubling me. First off, I am facing a challenge with an animation feature that I need to modify within the "popup" class for a gallery section on a website. Currently, when users load the page, a square image and background start ...

I can view the data retrieved in the console, but I am having difficulty displaying it on the screen

I have successfully retrieved data from the API, as indicated by the output in my console. However, I am facing issues in displaying this data on the webpage due to a potential error in my code structure. Despite this, I can confirm that the fetched data ...

Processing incoming requests with a loading interface in CodeIgniter

Is there a way to notify the user who sent the request whether or not the requested user will approve it? Optional: If there is no notification sent to the user who made the request, the requested user will have to wait for verification. For Example: Ima ...

Unable to create account using PHP

Every time I attempt to create an account, the data I receive is always problematic. The username must be between 3 and 15 characters I find it frustrating that the account creation never goes through successfully. What baffles me even more is that af ...

Tips on showcasing a collection of orders stored in a database using Vue.js

After successfully updating my orders post payment, I am wondering how I can showcase them on my Vue front end. Below is the HTML template displaying the list of orders made: <template> <div> <div v-for="order in orders&quo ...

When I select an option with an object, ng-model is receiving '[object Object]' instead of the actual object for <select> element

Referencing an example from Angular documentation: this link, specifically the section on "Using ngValue to bind the model to an array of objects." In the index.html file: <!doctype html> <html lang="en"> <head> <meta charset="UTF- ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...

Need help with decoding XML namespaces?

How can I use JavaScript/Ajax to parse values from the following XML snippet? <yweather:astronomy sunrise="6:34 am" sunset="8:38 pm"/> I've been attempting to retrieve the sunrise attribute with no success using this code: var response = tran ...

Struggling to transfer information between POST and GET requests in Node/Express

Just diving into node/express, currently developing a weather application that receives location data from a form submission <form method="POST" action="/"> <input id="input" type="text" name="city" placeholder="Search by city or zip code" /> ...

Tips for setting the textfield value in JSP using Javascript

I am in need of a way to create a random number that will be displayed in the textfield once the user clicks on the "Generate" button. Can someone guide me on how to assign the value of the "output variable" to the "randomNum" textfield? Sample HTML code: ...

Keeping calculated values in the React state can cause issues

In an attempt to develop a component resembling a transferlist, I have simplified the process substantially for this particular issue. Consider the following example: the react-admin component receives two inputs - a subset of selected items record[source ...

The ".splice()" method continuously removes the final element from an array

I have implemented a function on my form that allows me to add multiple file inputs for various images by clicking a button. Although this functionality is working correctly, I am facing an issue while trying to delete an input field using .splice. Instead ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

Sorting Columns in PrimeVue DataTable by Date and Time

I am using a PrimeVue DataTable () with the following structure: <DataTable :rows = "5" :value = "apiItems" > <Column v-for="data in columns" :field="data.field" :header="data.header&q ...

"Adjusting the height of Material UI card content to ensure fixed positioning at the bottom

Currently, I am working on mapping material-ui cards with dynamic content from a JSON object, resulting in varying card heights. I have successfully set a fixed height for each card, but the content is not aligned correctly. You can see the issue in this ...

ajaxStop and ajaxStart not functioning as expected

Currently working on a project to create a Wikipedia viewer, and running into an issue with the following code snippet: $(document).ready(function() { $(document).on('click', '#search_button', function() { ...

Angular 4 after ejection, coupled with automated end-to-end testing using Protractor/Selenium setup

I am attempting to conduct end-to-end tests using Protractor/Selenium on an Angular 4 project that has been ejected. Here is my package.json: ... "scripts": { "pree2e": "webdriver-manager update --standalone false --gecko false --quiet node", "e2 ...