Skip to content

Instantly share code, notes, and snippets.

@Madhuka
Created December 8, 2013 08:42
Show Gist options
  • Save Madhuka/7854709 to your computer and use it in GitHub Desktop.
Save Madhuka/7854709 to your computer and use it in GitHub Desktop.
Jasmine test with AJAX
function sendRequest(callbacks, configuration) {
$.ajax({
url: configuration.url,
dataType: "json",
success: function(data) {
callbacks.checkForInformation(data);
},
error: function(data) {
callbacks.displayErrorMessage();
},
timeout: configuration.remainingCallTime
});
}
describe("Ajax Tests", function() {
var configuration = {
url : "Car",
remainingCallTime : 30000
};
it("should make an Ajax request to the correct URL", function() {
spyOn($, "ajax");
sendRequest(undefined, configuration);
expect($.ajax.mostRecentCall.args[0]["url"]).toEqual(configuration.url);
});
it("should receive a successful response", function() {
spyOn($, "ajax").andCallFake(function(e) {
e.success({});
});
// Creatring some mock object for test
var callbacks = {
checkForInformation : jasmine.createSpy(),
displayErrorMessage : jasmine.createSpy(),
};
sendRequest(callbacks, configuration);
expect(callbacks.checkForInformation).toHaveBeenCalled();
//Verifies this was called
expect(callbacks.displayErrorMessage).not.toHaveBeenCalled();
//Verifies this was NOT called
});
it("should receive an Ajax error", function() {
spyOn($, "ajax").andCallFake(function(e) {
e.error({});
});
var callbacks = {
displayErrorMessage : jasmine.createSpy()
};
sendRequest(callbacks, configuration);
expect(callbacks.displayErrorMessage).toHaveBeenCalled();
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Spec Runner</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-1.3.1/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-1.3.1/jasmine.css">
<script type="text/javascript" src="lib/jasmine-1.3.1/jquery.min.js"></script>
<script type="text/javascript" src="lib/jasmine-1.3.1/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-1.3.1/jasmine-html.js"></script>
<script type="text/javascript" src="src/Car.js"></script>
<script type="text/javascript" src="spec/CarSpec.js"></script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment