2015-02-06 38 views
0

我想知道哪个是测试不返回任何东西(仅更改字段值)并包含异步调用的函数的最佳方法。Jasmine:包含异步调用的测试void函数

这个AngularJS控制器我想测试,服务我调用返回一个承诺(总是返回{名字:“约翰”}):

app.controller('MyCtrl', function($scope, AsyncService) { 

    $scope.greeting = ""; 
    $scope.error = 

    $scope.sayHello = function() { 

    AsyncService.getName().then(
     function(data){ 
      $scope.saludo = "Hello " + data.name; 
     }, 
     function(data){ 
       $scope.error = data; 
     } 
    ); 

    }; 

}); 

这将是规范,如果sayHello的功能都没有包含异步调用,但始终会失败,因为scope.greeting始终为空。

describe('Test My Controller', function() { 

    var scope, $httpBackend; 

    // Load the module with MainController 
    //mock Application to allow us to inject our own dependencies 
    beforeEach(angular.mock.module('app')); 

    //mock the controller for the same reason and include $rootScope and $controller 
    beforeEach(angular.mock.inject(function($rootScope, $controller,_$httpBackend_){ 

     //Mock the service to always return "John" 
     $httpBackend = _$httpBackend_; 
     $httpBackend.when('POST', 'http://localhost:8080/greeting').respond({name: "John"}); 

     //create an empty scope 
     scope = $rootScope.$new(); 
     //declare the controller and inject our empty scope 
     $controller('MyCtrl', {$scope: scope}); 
    })); 

    it('$scope.greeting should get filled after sayHello', function() { 
    expect(scope.greeting).toEqual(""); 
    scope.sayHello(); 
    expect(scope.greeting).toEqual("Hello John"); 
    });*/ 

}); 

我该如何使这个规范处理异步调用?我真的不知道如何以及在哪里使用Jasmine 2.0的“完成”标志。

+0

重复[http://stackoverflow.com/questions/21323996/angularjs-test-scope-methods-that-make-async-calls](http://stackoverflow .COM /问题/ 21323996/angularjs试验范围的方法,即,使-异步调用) – razvanz 2015-02-06 10:10:31

回答

1

使用$ q.defer()从服务模拟中返回getName函数中的承诺。然后通过创建您的控制器时,嘲笑到依赖关系:

beforeEach(inject(function($controller, _$rootScope_, $q) { 
    $rootScope = _$rootScope_; 
    deferred = $q.defer(); 

    asyncService = { 
     getName: function() { 
     } 
    }; 

    spyOn(asyncService, 'getName').and.returnValue(deferred.promise); 

    $scope = $rootScope.$new(); 

    createController = function() { 
     return $controller('MyCtrl', { $scope: $scope, AsyncService: asyncService }); 
    }; 
})); 

然后调用$scope.hello()电话deferred.resolve(data)l后,其中的数据是,你想从你的服务承诺返回的数据。然后调用$rootScope.$digest();

it('$scope.saludo should get filled after sayHello', function() { 
    //Arrange 
    var controller = createController(); 
    var data = { 
     name: 'John' 
    }; 

    //Act 
    $scope.sayHello(); 
    deferred.resolve(data); 
    $rootScope.$digest(); 

    //Assert 
    expect($scope.saludo).toEqual('Hello ' + data.name); 
}); 

Plunkr