业力如何测试这个角度代码?

时间:2016-01-19 11:26:21

标签: angularjs jasmine karma-runner karma-jasmine

$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

1 个答案:

答案 0 :(得分:1)

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

类似的东西:

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