Sam and I have been using Jasmine as our Javascript testing library for our Software Engineering project, mainly because I’ve used QUnit in the past and wanted to try something new. It also makes the tests in our group seem “uniform” in that Jasmine tests look a lot like RSpec, which is what the Rails team on our project is using. Our application has a RESTful Rails backend and a frontend written in Backbone.
We have a function in our Backbone view that calls a function on our Backbone model. The Backbone model talks to our RESTful backend and based on the response triggers the “success” or “error” callback functions provided by the view. Here is the pattern that we used to test this function:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('A Jasmine test', function() { | |
it('should be able to test async functions', function() { | |
// variable to check if our function call was successful | |
var wasSuccessful = null; | |
// Dummy Backbone model | |
var testModel = new TestModel(); | |
runs(function() { | |
// someAsyncFunction is an async function that calls the 'success' function in our params object | |
// if the call was successful. It calls the 'error' function in our params object otherwise. | |
testModel.someAsyncFunction({ | |
data: 'test', | |
success: function() { | |
wasSuccessful = true; | |
}, | |
error: function() { | |
wasSuccessful = false; | |
} | |
}); | |
}); | |
var timeout = 2000; | |
waitsFor(function() { | |
return wasSuccessful; | |
}, 'Async call should be a success', timeout); | |
runs(function() { | |
expect(wasSuccessful).toBe(true); | |
}); | |
}); | |
}); |
One thought on “Testing Async Functions with Jasmine”