M
M
mortyy2017-05-31 15:53:12
Angular
mortyy, 2017-05-31 15:53:12

How to test the service?

Test :

describe('Component: Login', function () {

  var ctrl;
  var $componentController;
  var $q;
  var $httpBackend;
  var _$rootScope;
  var $rest = {};

  beforeEach(module('bcsgm.main'));

  beforeEach(inject(function (_$componentController_, _$q_, _$rootScope_, _$httpBackend_, _$rest_) {
    $componentController = _$componentController_;
    $q = _$q_;
    _$rootScope = _$rootScope_;
    $httpBackend = _$httpBackend_;
    $rest = _$rest_;
    $httpBackend.whenGET(new RegExp('.*')).respond({$promise: $q.defer().promise});
    $httpBackend.whenPOST(new RegExp('.*')).respond({$promise: $q.defer().promise});
  }));


  describe('on Init', function () {

    beforeEach(function () {
      ctrl = $componentController('login', {$rest, _$rootScope}, {});
      _$rootScope.$digest();
      spyOn($rest, 'login');
    });

    it('should be defined ctrl', function () {
      expect(ctrl).toBeDefined();
    });

    it('should step be step', function () {
      expect(ctrl.step).toBe('login');
    });

    it('login response should be called once', function () {
      ctrl.username = 'user';
      ctrl.password = 'password';
      ctrl.login();
      expect($rest.login).toHaveBeenCalledTimes(1);
    })
  });

});

Method in controller:
function login() {
      if ($ctrl.captchaId) {
        if (!_.isEmpty($ctrl.captchaId) && !_.isEmpty($ctrl.captchaCode) && !_.isEmpty($ctrl.username) && !_.isEmpty($ctrl.password)) {
          $rest.login({
            captchaId: $ctrl.captchaId,
            captchaCode: $ctrl.captchaCode,
            username: $ctrl.username,
            password: $ctrl.password
          }).$promise.then(handleSuccessResponse, handleErrorResponse);
        }
      } else {
        if (!_.isEmpty($ctrl.username) && !_.isEmpty($ctrl.password)) {
          $rest.login({
            username: $ctrl.username,
            password: $ctrl.password
          }).$promise.then(handleSuccessResponse, handleErrorResponse);
        }
      }
    }

Factory with service :
function RestService($resource) {
    return $resource(null, null,
      {
        login: {url: '/portal/login', method: 'POST'},
      }
    );
  }

Running the 'login response should be called once' test throws TypeError: undefined is not an object (evaluating '$rest.login({
username: $ctrl.username,
password: $ctrl.password
}).$promise')
how to solve the problem ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2017-05-31
@mortyy

Well, you messed up your $rest service, an empty object gets instead of the original.
Add callable functions there, like this:

$rest.login = jasmine.createSpy('login').and.returnValue({$promise: $q.when()});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question