簡體   English   中英

使用$ stateChangeStart和$ rootScope測試UI路由器狀態

[英]Testing UI router states with $stateChangeStart and $rootScope

如何使用$ stateChangeStart或其他發出的事件進行測試?

我有以下代碼,從本質上講,該代碼檢查用戶是否已登錄,如果未登錄,則重定向到app.login狀態

app.run(function ($rootScope, $state, AuthenticationService) {

  $rootScope.AuthenticationService = AuthenticationService
  $rootScope.isLoggedIn = AuthenticationService.getIsLoggedIn

  if (!$rootScope.isLoggedIn()) {
    $state.go('app.login')
  }
  // Catch all errors on state change
  $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
    $state.go('app.home')
  })

  // Sets up the role requirements per state
  $rootScope.$on('$stateChangeStart', function (event, toState) {
    if (AuthenticationService.getIsLoggedIn()) {
    } else {
      if (toState && toState.name !== 'app.login') {
        $state.go('app.login')
      }
    }
  })
})

我正在嘗試達到的測試:

'use strict'

describe('Controller', function () {

  var $scope
    , $state
    , $rootScope
    , AuthenticationService
    , $controller

  beforeEach(module('replanApp'))

  beforeEach(inject(function ($injector) {
    $state = $injector.get('$state')
    $rootScope = $injector.get('$rootScope')
    AuthenticationService = $injector.get('AuthenticationService')
    $scope = $rootScope.$new()
    $controller = $injector.get('$controller')
  }))

  describe('Initializers', function () {
    it('should redirect to /login if the user is not logged in', function () {
      $state.go('app.admin.index')
      $rootScope.$apply()
      assert.notOk(AuthenticationService.getIsLoggedIn())
      assert.equal($state.current.name, 'app.login')
    })
  })
})

它基本上應該進入一個狀態,然后$rootScope.$on('$stateChangeStart', fn(){})應該已經看到用戶尚未登錄,並將其轉移到app.login狀態。

但我收到AssertionError: expected 'app.admin.index' to equal 'app.login'

如何使用$ stateChangeStart和其他事件來完成測試?

我將修改測試以檢查是否已使用'app.login'調用了$state.go ,而不是嘗試檢查當前狀態是什么:

describe('Initializers', function () {
    beforeEach(function(){
        spyOn($state,'go');
    });
    it('should redirect to /login if the user is not logged in', function () {
      $state.transitionTo('app.admin.index');
      $rootScope.$apply();
      assert.notOk(AuthenticationService.getIsLoggedIn());
      expect($state.go).toHaveBeenCalledWith('app.login');
    });
  });

我不能保證會修復您的測試,但是它將使它更像一個單元測試,因為它不會依賴$state.go來設置當前狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM