噶如何测试这个angular代码?

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

我将如何测试此功能?针对 scope.loggedIn 的测试失败,因为它仍然是 false

如果您的 api 发出 http 请求,您可以使用 $httpBackend 模拟 http 调用 https://docs.angularjs.org/api/ngMock/service/$http后端

像这样:

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