AngularJS - Create and resolve promises in one line

So much of my test code had the same 3 lines in it to create a promise, and immediately resolve it. Ya know, creating stub promises so your tests don’t cross too many boundaries.

Create and resolve() a promise

var deferred = $q.defer();
deferred.resolve(‘This is the old way’);
return deferred.promise;

Replace it in one line!

return $q.when(‘This is the new way’);

Same for reject()

var deferred = $q.defer();
deferred.reject(‘This is the old way’);
return deferred.promise;

Replace it in one line!

return $q.reject(‘This is the new way’);

Notes

Yes it’s strange that to resolve you use .when(). I think this is just a quirk of AngularJS and will be changed in Angular 2 since ES6 supports similar (called .reject & .resolve) and it would be not smart to continue to do something different.