【问题标题】:ui-router test failed with event.preventDefault() in $stateChangeStartui-router 测试失败,$stateChangeStart 中的 event.preventDefault()
【发布时间】:2015-04-23 22:05:45
【问题描述】:

我的角度测试有问题。

describe('Routes test', function() {
    //Initialize global variables
    var $state,
        $location;

    // Load the main application module
    beforeEach(module("MyApp"));

    beforeEach(inject(function(_$location_, _$state_, $templateCache) {
        $state = _$state_;
        $location = _$location_;

        // We need add the template entry into the templateCache if we ever
        // specify a templateUrl
        $templateCache.put('signin.admin.view.html', 'signin');
    }));

    it('should be redirect to signin if user is not loggedin', function() {
        $rootScope.$apply(function() {
            $location.path('/');
        });
        expect($state.current.name).toEqual('signin');
        console.log($state.current);
    });
});

所以我期待登录状态,因为用户没有登录。但是从控制台 $state.current 仍然是:

Object{name: '', url: '^', views: null, abstract: true}

为了重定向我使用了这个代码:

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if (toState.name.indexOf('signin') === 0 ) {
        if( loggedIn ) {
            event.preventDefault();
            $state.go('layout.dashboard');
        }
    } else {
        if( !loggedIn ) {
            event.preventDefault();
            $state.go('signin');
        }
    }
});

变量 loggedIn 为假。所以我不明白,当我在浏览器中手动进行测试时 $state.current 符合预期。但不在本次测试中。

感谢您的帮助。

【问题讨论】:

    标签: angularjs angular-ui-router karma-jasmine


    【解决方案1】:

    与其做$rootScope.$apply(...)不如试试做:

    $location.path('/');
    $rootScope.$broadcast('$locationChangeSuccess');
    

    UI 路由器侦听由 Angular 的 $location 服务触发的 $locationChangeSuccess 事件。当它捕捉到这个事件时,它会找到正确的状态并开始导航到那个状态,从而触发$stateChangeStart 事件。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2021-05-19
      • 2019-03-09
      • 1970-01-01
      相关资源
      最近更新 更多