AngularJS : Testing factory that returns $http pro

2020-04-20 09:09发布

问题:

Trying to test an angular service that returns an $http GET request and the then handler, but I'm not able to test that the logic actually works inside of the then function. Here is a basic, truncated version of the service code:

angular.module('app').factory('User', function ($http) {
  var User = {};

  User.get = function(id) {
    return $http.get('/api/users/' + id).then(function (response) {
      var user = response.data;
      user.customProperty = true;  
      return user;
    });
  };

  return User;
});

And here is the test:

beforeEach(module('app'));
beforeEach(inject(function(_User_, _$q_, _$httpBackend_, _$rootScope_) {
  $q = _$q_;
  User = _User_;
  $httpBackend = _$httpBackend_;
  $scope = _$rootScope_.$new();
}));

afterEach(function () {
  $httpBackend.verifyNoOutstandingRequest();
  $httpBackend.verifyNoOutstandingExpectation();
});

describe('User factory', function () {

  it('gets a user and updates customProperty', function () {
    $httpBackend.expectGET('/api/users/123').respond({ id: 123 });
    User.get(123).then(function (user) {
      expect(user.customProperty).toBe(true);  // this never runs
    });

    $httpBackend.flush();
  });

});

I feel like I've tried pretty much everything to test the logic in the then call, so if someone can offer suggestions I would greatly appreciate it.

Edit: my problem was also due to nonstandard injection practices, so the answer below worked outside of that.

回答1:

A few things need to be changed

  • Use whenGET instead of expectGET in order to fake a response
  • In the test then callback, set the response to a variable available outside the callback so you can test it in an expect call
  • Make sure the expect call is outside any callbacks, so it always runs and shows any failures.

Putting it all together:

it('gets a user and updates customProperty', function () {
  $httpBackend.whenGET('/api/users/123').respond({ id: 123 });
  User.get(123).then(function(response) {
    user = response;
  })
  $httpBackend.flush();
  expect(user.customProperty).toBe(true); 
});

As can be seen at http://plnkr.co/edit/9zON7ALKnrKpcOVrBupQ?p=preview