Skip to content

Instantly share code, notes, and snippets.

@ragaskar
Forked from JulesAU/gist:1145534
Created August 19, 2011 13:08
Show Gist options
  • Save ragaskar/1156753 to your computer and use it in GitHub Desktop.
Save ragaskar/1156753 to your computer and use it in GitHub Desktop.
/*
We have two classes: resultRenderer and dbQuery
resultRenderer will ask dbQuery to perform a database query, and asyncronously receives the results
*/
function resultRenderer(query) { this._query = query }
resultRenderer.prototype = {
queryResultsAndRender: function () {
this._query.runQueryAsync(this.renderResults.bind(this));
},
renderResults: function (results) {
// now render them!
}
}
function dbQuery() {}
dbQuery.prototype = {
runQueryAsync: function (callback) {
// query the database, and callback once we have results:
callback(queryResults);
}
}
// to test resultRenderer using a mocked dbQuery, we write something like:
query = new dbQuery;
fakeResponse = { some: "reasonable data"}
spyOn(dbQuery, 'runQueryAsync').andCallFake(function(callback) {
callback(fakeResponse);
});
renderer = new resultRenderer(query);
spyOn(renderer, 'resultsRenderer');
renderer.queryResultsAndRender();
//two options here:
//1) expect that our callback got the right args, unit test callback with another spec.
expect(renderer.resultsRenderer).to.haveBeenCalledWith(fakeResponse);
//2) test the result of our callback getting the args.
expect(someOtherThingThatsTheResultOfOurRenderer).toBe(inTheDOMEtc);
@sappleg
Copy link

sappleg commented Jul 30, 2013

@ragaskar

How would we test the case where I have a function that calls a service that performs an ajax call. I pass the service function a parameter and a callback. How would I mock the calling of that callback function and test the parameters in which the original service function was called with. For example, here is the function we want to test

$scope.destroy = function(comment) {
    Comment.remove({id: comment.id}, function() {
        $scope.comments = _.without($scope.comments, comment);
    })
};

I want to test that Comment.remove is called with an object and a callback function. Then I want to test the functionality of that callback function (e.g. an element being removed from $scope.comments).

Any suggestions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment