2015-02-06 39 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