Reputation: 1022
I am currently trying to test my javascript code using jasmine. It has been ok until now where i need to mock ajax requests. I currently use jasmine 1.2 and mock-ajax.js My code is as follows:
I have a handler.js file which basically has a number of ajax requests. I am using require.js which to read the config js file which has the relevant urls.
define(['urlConfig'], function (urlConfig) {
return {
getAllCustomers: function () {
return $.ajax({
url: config.url,
dataType: 'json',
xhrFields: {
withCredentials: true
},
});
}
}
So basically i have now created a spec to test to see if the ajax requests do get hit.
define(["/../dependencies/squire.js"], function(Squire) {
var injector;
beforeEach(function() {
injector = new Squire();
jasmine.Ajax.install();
});
describe("handler", function() {
var mockData = {
data: [
{
reference: "ref1",
name: "bob"
},
{
reference: "ref2",
name: "fred"
}
]
}
function loadModule() {
mockHandler();
}
function mockHandler() {
injector.mock('handlers/Handler', {
getAllCustomers: function() {
return {
then: function(callback) {
callback(mockData);
}
}
}
});
};
describe("get all customers", function() {
beforeEach(function() {
loadModule();
});
it('expect to get all account details on request', function() {
spyOn($, "ajax").andCallFake(function(options) {
options.success();
});
var callback = jasmine.createSpy();
mockHandler().getCustomerDetails(callback);
expect(callback).toHaveBeenCalled();
});
});
});
});
Not sure if the above is correct but also getting an error stating TypeError: 'undefined' is not a function (evaluating 'spyOn($, "ajax").andCallFake(function(options)
Any help would be greay
Upvotes: 0
Views: 2644
Reputation: 3893
If you need help mocking jQuery ajax calls check this question:
How do I verify jQuery AJAX events with Jasmine?
It helped me.
Upvotes: 0
Reputation: 35
The function .andCallFaketo()
changed to .and.callFake()
in version 2.0 of Jasmine. Like this example:
spyOn().and.callFake(function() {
return 1001;
});
Upvotes: 2