Skip to content

Instantly share code, notes, and snippets.

@matiboy
Created October 31, 2013 02:56
Show Gist options
  • Select an option

  • Save matiboy/7243743 to your computer and use it in GitHub Desktop.

Select an option

Save matiboy/7243743 to your computer and use it in GitHub Desktop.
var jasmineNG = {};
//set $q in your test
jasmineNG.$q = null;
//Could make similar to test a failing promise
jasmineNG.createPromiseReturningSpy = function() {
var deferred = jasmineNG.$q.defer();
// Use .andReturn to simply return a promise
var spy = jasmine.createSpy().andReturn(deferred.promise);
// Add resolve and reject functionalities
spy.andResolveWith = function(val) {
deferred.resolve(val);
return spy; // chain
};
spy.andRejectWith = function(val) {
deferred.reject(val);
return spy;
};
return spy;
}
// Usage:
// var spiedFunction = jasmineNG.createPromiseReturningSpy(); // always returns a non-resolved, non-rejected promise
// var spiedFunctionResolved = jasmineNG.createPromiseReturningSpy().andResolveWith('hello'); // promise with resolve
// var spiedFunctionResolved = jasmineNG.createPromiseReturningSpy().andRejectWith('no good'); // promise with reject
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment