I'm using AngularJS 1.2.10. My application works, the problem is only in unit tests. When performing an update (HTTP PUT) with $httpBackend, the callbacks are not invoked, so my test fails
The controller method I want to test looks like:
$scope.updateName = function(name, release) {
$scope.isLoading = true;
release.name = name;
release.$update({ projectId: $scope.projectId }, function() {
$scope.isLoading = false;
}, function(err) {
console.log(err);
});
};
The service it uses is:
angular.module('app.release').factory('ReleaseService', ['$resource', function($resource) {
return $resource('projects/:projectId/releases/:releaseId', {
releaseId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}]);
And the unit test:
it('$scope.updateName() should update release name', inject(function(ReleaseService) {
var data = function(){
return {
_id: '456',
name: 'v1.0',
description: 'A Release'
};
};
// mock release object
var release = new ReleaseService(data());
scope.release = release;
scope.projectId = '123';
$httpBackend.expectPUT('projects/123/releases/456').respond({
_id: '456',
name: 'a new name',
description: 'A Release'
});
scope.updateName('a new name', release);
$httpBackend.flush();
expect(scope.isLoading).toBe(false); // fails
}));
Update: I tried to add scope.$digest() just before the final expect(), just like in Why is my $q deferred not resolving in Angular unit test?, but it didn't work in my case :(
This is how I finally fixed the test:
it('$scope.updateName() should update release name', inject(function(ReleaseService) {
var data = {
_id: '456',
name: 'v1.0',
description: 'A Release'
};
var expectedResponse = {
_id: '525a8422f6d0f87f0e407a33',
name: 'a new name',
description: 'A Release about Agile Warlock'
};
// mock release object
var release = new ReleaseService(data);
scope.release = release;
scope.projectId = '123';
$httpBackend.expectPUT('projects/123/releases/456').respond(expectedResponse);
scope.updateName('a new name', release);
$httpBackend.flush();
expect(scope.isLoading).toBe(false);
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With