I am using Jasmine 2.5.2 to write unit tests for code that performs Ajax requests using jQuery 3.1.1 . I would like to mock out the Ajax call, providing my own response status and text.
I am using the Jasmine ajax plug-in (https://github.com/pivotal/jasmine-ajax).
Following the example on https://jasmine.github.io/2.0/ajax.html, which uses the XMLHttpRequest object, works fine.
describe("mocking ajax", function() {
describe("suite wide usage", function() {
beforeEach(function() {
jasmine.Ajax.install();
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it("specifying response when you need it", function() {
var doneFn = jasmine.createSpy("success");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(args) {
if (this.readyState == this.DONE) {
doneFn(this.responseText);
}
};
xhr.open("GET", "/some/cool/url");
xhr.send();
expect(jasmine.Ajax.requests.mostRecent().url).toBe('/some/cool/url');
expect(doneFn).not.toHaveBeenCalled();
jasmine.Ajax.requests.mostRecent().respondWith({
"status": 200,
"contentType": 'text/plain',
"responseText": 'awesome response'
});
expect(doneFn).toHaveBeenCalledWith('awesome response');
});
});
});
NB: this differs slightly from the documented example, had to change jasmine.Ajax.requests.mostRecent().response()
to jasmine.Ajax.requests.mostRecent().respondWith()
.
When I use jQuery Ajax, the doneFn is never called.
describe("mocking ajax", function() {
describe("suite wide usage", function() {
beforeEach(function() {
jasmine.Ajax.install();
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it("specifying response when you need it", function() {
var doneFn = jasmine.createSpy("success");
$.ajax({
method: "GET",
url: "/some/cool/url"})
.done(function(result) {
doneFn(result);
});
expect(doneFn).toHaveBeenCalledWith('awesome response');
});
});
});
Jasmine states that
Jasmine-Ajax mocks out your request at the XMLHttpRequest object, so should be compatible with other libraries that do ajax requests.
$.ajax returns a jqXHR from 1.4.x and not XMLHttpRequest - does this break support with Jasmine Ajax?