[英]AngularJS controller instantiation in unit tests - functions not binding to scope values
我有一個將數據同步返回到控制器的服務:
angular.module('app').controller(function($scope, myService) {
$scope.foo = myService.getFoo();
});
這在瀏覽器中工作正常。 在我的單元測試中, $scope.foo
是未定義的:
beforeEach(function () {
module('app');
myService = jasmine.createSpyObj('myService', ['getFoo']);
inject(function($controller, $rootScope) {
$scope = $rootScope.$new();
ctrl = $controller('ModelSliderCtrl', {
myService: myService,
$scope: $scope
});
});
});
it('should have foo on the scope', function() {
myService.getFoo.and.returnValue({});
expect(myService.getFoo).toHaveBeenCalled(); // PASS
$scope.$digest();
expect($scope.foo).toBeDefined(); // FAIL - $scope.foo is undefined
});
這確實在瀏覽器中測試兩種工作方式:
angular.module('app').controller(function($scope, myService) {
$scope.init = function() {
$scope.foo = myService.getFoo();
};
$scope.init();
});
。
it('should have foo on the scope', function() {
myService.getFoo.and.returnValue({});
$scope.init();
expect(myService.getFoo).toHaveBeenCalled(); // PASS
expect($scope.foo).toBeDefined(); // PASS
});
我想相信我精通Angular,Jasmine和JavaScript。 我也問過一些同樣困惑的同事。
誰能告訴我這是怎么回事?
您正在設置一個模擬
it('should have foo on the scope', function() {
myService.getFoo.and.returnValue({});
實例化控制器后。 那時設置模擬已經為時已晚,因為您立即執行init()
,所以在實例化控制器之前先進行模擬。
myService = jasmine.createSpyObj('myService', ['getFoo']);
myService.getFoo.and.returnValue({});
inject(function($controller, $rootScope) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.