samedi 25 juillet 2015

Unit test a method on a factory with httpbackend

I have a simple AuthService service. I want to unit test the changePassword method.

How can I test that the correct payload was posted to the LoginAuthService.changePassword method? Am I doing this right?

AuthService service

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

Unit test

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');

    });

  });

Aucun commentaire:

Enregistrer un commentaire