AngularJS: test $ resource PUT request

I am using AngularJS 1.2.10. My application works, the problem is only in unit tests. When updating (HTTP PUT) with $ httpBackend, callbacks are not called, so my test fails

The controller method I want to test looks like this:

$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);
    });
};

Service Used:

angular.module('app.release').factory('ReleaseService', ['$resource', function($resource) {
    return $resource('projects/:projectId/releases/:releaseId', {
        releaseId: '@_id'
    }, {
        update: {
            method: 'PUT'
        }
    });
}]);

And 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 an area. $ digest () before the final wait (), as in Why is my $ q deferred without allowing in the Angular unit test? but in my case it didn’t work :(

+3
source share
1 answer

Here's how I finally installed 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);
}));
+3
source

All Articles