单元测试http在httpbackend的工厂上发布正确的有效负载

时间:2015-07-25 22:38:06

标签: angularjs unit-testing jasmine angular-services

我有一个简单的AuthService服务。我想对changePassword方法进行单元测试。

如何测试是否已将正确的有效负载发布到LoginAuthService.changePassword方法?我这样做了吗?

AuthService服务

angular.module('example')
  .factory('AuthService', ['$http',
    function($http) {
      var authService = {};

      authService.changePassword = function(email) {
        var payload = {
          email: email,
          action: 'changePassword'
        };

        return $http.post('/api/users', payload)
          .then(function(res) {
            return res;
          });
      };

      return authService;
    }
  ]);

单元测试

describe('#changePassword', function() {
    beforeEach(function() {
      // this just does some basic test setup
      _setup();

      // should i use httpBackend? or is there a better way
      $httpBackend
        .expectPOST('/api/users')
        .respond(200, 'test success');
    });

    it('should call change password', function() {
      var response;

      // setup
      LoginAuthService.changePassword('test@email.com')
        .then(function(res) {
          response = res;
        });

      // flush
      $httpBackend.flush();

      expect(response.data).toEqual('test success');

    });

  });

1 个答案:

答案 0 :(得分:1)

是的,对我来说似乎没问题。您可以添加有效负载:

$httpBackend
  .expectPOST('/api/users', yourExpectedPaylod)
  .respond(200, 'test success');