如何使用$ 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和其他活動的測試?
順便說一句,你必須在'$ state.go('app.login')'之前調用'event.preventDefault();'。 – xpepermint