Iām trying to use Jasmine spies for testing a controller that calls query on a $resource. I can get a successful test when I write my call to the resource as follows (implementation 1 in the plunk linked below)
function($scope, bagelApiService) {
bagelApiService
.query()
.$promise
.then(function(bagelsResponse) {
$scope.bagels = bagelsResponse;
$scope.somethingAfterBagelsLoad = true;
});
}
But I would rather call the resource like this (implementation 2 in the plunk linked below)
function($scope, bagelApiService) {
bagelApiService.query(function(bagelsResponse) {
$scope.bagels = bagelsResponse;
$scope.somethingAfterBagelsLoad = true;
});
}
Here is my spec
describe('BreakfastCtrl', function() {
var $q,
$rootScope,
_scope,
mockBagelsResponse = [{name: 'foobagel'}, {name: 'barbagel'}];
beforeEach(module('BreakfastApp'));
beforeEach(inject(function($controller, $q, $rootScope, bagelApiService) {
_scope = $rootScope.$new();
var queryDeferred = $q.defer();
spyOn(bagelApiService, 'query').andReturn({$promise: queryDeferred.promise});
$controller('BreakfastCtrl', {
'$scope': _scope,
'bagelApiService': bagelApiService
});
queryDeferred.resolve(mockBagelsResponse);
$rootScope.$apply();
}));
it('should set scope.bagels', function() {
expect(_scope.bagels).toEqual(mockBagelsResponse);
});
});
Any idea why implementation 2 fails the test (even though it runs fine), and how the test can be written to pass with implementation 2?