$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
。
答案 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
});