0
我想單元測試$scope.$watch
在控制器中,我不知道爲什麼$scope.$apply()
在測試代碼導致意外的請求錯誤,如Error: Unexpected request: GET /locales/en.json
。這是控制器的其他部分,它爲什麼涉及這裏?
但是,如果我評論$scope.$apply
,則不會發生此錯誤,但當然在這種情況下無法觸發$ watch。我是否需要嘲笑像$httpBackend.whenGET('/locales/en.json').respond('');
這樣的請求?
控制器:
$scope.$watch(function(){
return $location.path();
}, function() {
$scope.currentPath = $location.path().match(/\/[a-z0-9A-Z_]*/)[0];
$scope.currentNav = 'menu.' + $scope.currentPath.replace('/', '');
});
茉莉:
describe('homeController', function() {
beforeEach(module('homeApp'));
var $rootScope, $scope, controller, $httpBackend, $location, $route, $window
beforeEach(inject(function($controller, _$rootScope_, _$httpBackend_, _$location_, _$route_, _$window_) {
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
controller = $controller('homeController', {$scope: $scope});
$httpBackend = _$httpBackend_;
$location = _$location_;
$route = _$route_;
$window = _$window_;
}));
describe('watch path', function() {
it('should change currentPath and currentNav', function() {
$location.path('/dashboard');
$scope.$apply();
$location.path('/images');
$scope.$apply();
expect($scope.currentPath).toBe('/images')
expect($scope.currentNav).toBe('menu.images')
})
})
})
更新:
它嘲諷所需要的所有的http請求後工作。但仍然想知道爲什麼它會影響這些請求。
作爲'$ scope.watch'需要在這裏調用'$ scope.apply'的參數是你的$ scope.watch導致問題 –