jackdaw
jackdaw

Reputation: 2314

Karma how to test this angular code?

$scope.login = function(){

  api.getToken($scope.username, $scope.password, function(){

    $scope.loggedIn = true;

  });
};

it('should work', function(){
  scope.login();
  expect(scope.loggedIn).toBe(true); // fails
});

How would I test this function? Testing against scope.loggedIn fails as it remains false.

Upvotes: 0

Views: 29

Answers (1)

If your api makes http requests, You can use $httpBackend to mock http calls https://docs.angularjs.org/api/ngMock/service/$httpBackend

something like this:

var $httpBackend;

beforeEach(inject(function($injector){
    $httpBackend = $injector.get('$httpBackend');
}

it('should work', function(){

  $httpBackend.expect('POST', 'http://my-api/login').respond(200, { status: "ok" });
  scope.login();
  $httpBackend.flush();
  expect(scope.loggedIn).toBe(true); // fails
});

Upvotes: 1

Related Questions