user2624124
user2624124

Reputation: 11

Jasmine calling function with ajax returned value

I want to test the "addGroup" function using Jasmine. I get the following error:

Error: Expected spy modifyMyHtml to have been called.at null.

I don't know what is the best way to test the addGroup function. Please HELP.....

var myRecord = {

   addGroup: function(groupNumber) {

        $.when(myRecord.getHtml())
        .done(function(returnedHtml){
            myRecord.modifyMyHtml(returnedHtml);           
        });
    },

    getHtml: function() {
        return $.ajax({url: "myHtmlFile.html", dataType: "html" });
    },
    // adds options and events to my returned HTML
    modifyMyHtml: function(returnedHtml) {
        $('#outerDiv').html(returnedHtml);
        var myOptions = myRecord.getOptions();
        $('#optionsField').append(myOptions);
        myRecord.bindEventsToDiv();
    },
}

====JASMINE TEST

describe("Configure Record page", function() {
    var fixture;

    jasmine.getFixtures().fixturesPath = "/test/" ;
    jasmine.getFixtures().load("myHtmlFile.html");
    fixture = $("#jasmine-fixtures").html();

    describe("addGroup", function(){
        beforeEach(function() {
            var groupNumber = 0;
            spyOn(myRecord, "getHtml").andCallFake(function(){
                return $.Deferred().promise();
            });
            spyOn(myRecord, "modifyMyHtml");
            myRecord.addGroup(groupNumber);
        });

        it("Should call getHtml", function() {
            expect(myRecord.getHtml).toHaveBeenCalled();
        });

        it("Should call modifyMyHtml", function() {             
            expect(myRecord.modifyMyHtml).toHaveBeenCalled();  ==>FAILS
        });         
    }); 
});

Upvotes: 0

Views: 245

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 111082

You have to resolve the promise before you return em in your andCallFake.

spyOn(myRecord, "getHtml").andCallFake(function(){
  return $.Deferred().resolve ().promise();
});

Btw. you should not test that the function on the object you wanna test are called, but that the html in the DOM are set with the right html

it("Should call modifyMyHtml", function() {    
   spyOn(myRecord, "getHtml").andCallFake(function(){
      return $.Deferred().resolveWith(null, 'returnedHtml').promise();
   });         
   expect($('#outerDiv').html).toEqual('returnedHtml')
});   

Upvotes: 1

Related Questions