Jasmine Fiddle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/boot.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.5.2/jasmine.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine-ajax/3.3.1/mock-ajax.js"></script>
JavaScript
var testObj = {
ajaxFunction: function(url) {
$.ajax({
url: url
}).done(this.successFunction.bind(this));
},
successFunction: function(data) {
alert("DATA IS: "+data);
console.log(data);
}
}
describe('ajax test suite', function() {
beforeEach(function() {
jasmine.Ajax.install();
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
it('sample test', function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(args) {
if (this.readyState == this.DONE) {
testObj.successFunction(this.responseText);
}
};
spyOn(testObj, 'successFunction').and.callThrough();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
xhr.send();
expect(jasmine.Ajax.requests.mostRecent().url).toBe('https://jsonplaceholder.typicode.com/posts/1');
expect(testObj.successFunction).not.toHaveBeenCalled();
jasmine.Ajax.requests.mostRecent().respondWith({
"status": 200,
"contentType": 'text/plain',
"responseText": 'awesome response'
});
expect(testObj.successFunction).toHaveBeenCalledWith('awesome response');
});
});