简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM