我的主控制器中有一个简单的功能,可以根据ui.router的$scope.loading
和$stateChangeStart
事件更新$stateChangeSuccess
。
$scope.$on('$stateChangeStart', function(event, toState) {
if (toState.resolve) {
$scope.loading = true;
}
});
$scope.$on('$stateChangeSuccess', function(event, toState) {
if (toState.resolve) {
$scope.loading = false;
}
});
这很有效,直到我尝试进行单元测试。我找不到触发$stateChangeSuccess
事件的方法。
我的Jasmine单元测试看起来像这样:
it('should set $scope.loading to true', function () {
expect(scope.loading).toBe(false);
$state.go('home');
expect(scope.loading).toBe(true);
scope.$digest();
expect(scope.loading).toBe(false);
});
测试失败,因为$stateChangeSuccess
永远不会触发。任何想法都会非常感激。
答案 0 :(得分:1)
目前这对我有用。
您只需要$broadcast
该事件。请阅读下面的一些伪代码。我希望这会对你有所帮助。
// Note: this is pseudocode
// controller
// assumes you have your usual setup to support this controller.
// assumes this controller is attached to a component or angular controller.
function myController() {
var vm = this;
vm.isHappy = false;
$scope.$on('$stateChangeSuccess', function(event, toState) {
if (toState.name === 'myState') {
vm.isHappy = true;
}
});
}
// test
// assumes several things
// * ctrl is the currently mocked controller
// * has all the necessary setup & injections (such as $rootScope).
// * testing framework is Jasmine
describe('What happens when I go to my happy place?', function() {
it('should be visible to all that I am happy.', function() {
expect(ctrl.isHappy).toBeFalsy();
$rootScope.$broadcast('$stateChangeSuccess', {
'name': 'myState'
});
// or $scope.$broadcast
expect(ctrl.isHappy).toBeTruthy();
}
});