user1184100 user1184100 - 2 months ago 11
Javascript Question

Callback function not get called in jasmine test code

I'm using jasmine 2.0 for testing and I'm spying on the jquery ajax and returning a promise.
In the done() function method displayContent() doesn't get called but the console message above it gets shown up. Where am I going wrong ?

test.js

it(..., function() {
var data = {"name" : "John Doe"};
spyOn($, 'ajax').and.callFake(function (req) {
var d = $.Deferred();
d.resolve(data);
return d.promise();
});

app.doSomething();
expect(app.doSomething).toHaveBeenCalled();
})


app.js

app.getData = function() {
var jsonData = app.loadEmpData(); //gets replaced by spy and returns resolve(data);
jsonData.done(function(data) {
console.log("shows up in the console");
app.displayContent(data); // doesn't get called
});
jsonData.fail(function(){
console.log("error loading data");
});
}

app.loadEmpData = function() {
return $.getJSON("/employee.json");
}

app.displayContent = function() {
console.log("some content");
}

app.doSomething = function() {
app.getData();
}

Answer

Spy on the displayContent() and check if it is called or not. I modified your test and displayContent() was called. Replace with this code and check.

it("some test", function() {
    var data = {"name" : "John Doe"};
    spyOn($, 'ajax').and.callFake(function (req) {
        var d = $.Deferred();
        d.resolve(data);   
        return d.promise();
    });
    spyOn(app, 'displayContent').and.callThrough();
    app.getData();
    expect(app.displayContent).toHaveBeenCalled();
});

In Jasmine 2.0 and.callThrough(); will delegate to the actual implementation of displayContent().