Monday, May 20, 2024
21
rated 0 times [  24] [ 3]  / answers: 1 / hits: 53797  / 11 Years ago, fri, december 6, 2013, 12:00:00

I'm having some trouble unit testing the router in my application, which is built on the Angular ui router. What I want to test is whether state transitions change the URL appropriately (there will be more complicated tests later, but this is where I'm starting.)



Here is the relevant portion of my application code:



angular.module('scrapbooks')
.config( function($stateProvider){
$stateProvider.state('splash', {
url: /splash/,
templateUrl: /app/splash/splash.tpl.html,
controller: SplashCtrl
})
})


And the testing code:



it(should change to the splash state, function(){
inject(function($state, $rootScope){
$rootScope.$apply(function(){
$state.go(splash);
});
expect($state.current.name).to.equal(splash);
})
})


Similar questions on Stackoverflow (and the official ui router test code) suggest wrapping the $state.go call in $apply should be enough. But I've done that and the state is still not updating. $state.current.name remains empty.


More From » unit-testing

 Answers
1

Been having this issue as well, and finally figured out how to do it.



Here is a sample state:



angular.module('myApp', ['ui.router'])
.config(['$stateProvider', function($stateProvider) {
$stateProvider.state('myState', {
url: '/state/:id',
templateUrl: 'template.html',
controller: 'MyCtrl',
resolve: {
data: ['myService', function(service) {
return service.findAll();
}]
}
});
}]);


The unit test below will cover testing the URL w/ params, and executing the resolves which inject its own dependencies:



describe('myApp/myState', function() {

var $rootScope, $state, $injector, myServiceMock, state = 'myState';

beforeEach(function() {

module('myApp', function($provide) {
$provide.value('myService', myServiceMock = {});
});

inject(function(_$rootScope_, _$state_, _$injector_, $templateCache) {
$rootScope = _$rootScope_;
$state = _$state_;
$injector = _$injector_;

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

it('should respond to URL', function() {
expect($state.href(state, { id: 1 })).toEqual('#/state/1');
});

it('should resolve data', function() {
myServiceMock.findAll = jasmine.createSpy('findAll').and.returnValue('findAll');
// earlier than jasmine 2.0, replace and.returnValue with andReturn

$state.go(state);
$rootScope.$digest();
expect($state.current.name).toBe(state);

// Call invoke to inject dependencies and run function
expect($injector.invoke($state.current.resolve.data)).toBe('findAll');
});
});

[#73871] Thursday, December 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samir

Total Points: 145
Total Questions: 90
Total Answers: 89

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;