Ajax test code throwing error

倾然丶 夕夏残阳落幕 提交于 2019-12-12 04:23:38

问题


I am testing a code using jasmine and creating a mock object for ajax method

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

to test the following piece of code

$.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!!!');
        });
    },

It's throwing an error cannot read done of undefined . Do I need to create a spy for that also . Please help with the code to do so


回答1:


Issues with your code:

  • You are spying it right but you need to send in a promise object back via your spy. Basically you need to return something like this ==> return new $.Deferred().resolve(dummyData).promise();
  • There are multiple ways to create a deferred object/promise object. I suggest you to read both Promise & Deferred
  • Also could you explain where your $promise is coming from? is this some feature of require.js?

Below is one way to fake the 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 lengh 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);
  });
});


来源:https://stackoverflow.com/questions/41261559/ajax-test-code-throwing-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!