Estou tendo uma unidade de problemas testando o roteador em meu aplicativo, que é construído no roteador de interface de usuário angular. O que eu quero testar é se as transições de estado mudam a URL apropriadamente (haverá testes mais complicados depois, mas é aí que eu estou começando).
Aqui está a parte relevante do código do meu aplicativo:
angular.module('scrapbooks') .config( function($stateProvider){ $stateProvider.state('splash', { url: "/splash/", templateUrl: "/app/splash/splash.tpl.html", controller: "SplashCtrl" }) })
E o código de teste:
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"); }) })
Perguntas semelhantes sobre o Stackoverflow (e o código oficial de teste do roteador ui) sugerem que a conversão de $ state.go em $ apply seja suficiente. Mas eu fiz isso e o estado ainda não está atualizando. $ state.current.name permanece vazio.
Também tive esse problema e finalmente descobri como fazê-lo.
Aqui está um estado de amostra:
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(); }] } }); }]);
O teste de unidade abaixo irá cobrir o teste da URL com parâmetros e a execução das resoluções que injetam suas próprias 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'); }); });
Se você quiser verificar apenas o nome do estado atual, é mais fácil usar $state.transitionTo('splash')
it('should transition to splash', inject(function($state,$rootScope){ $state.transitionTo('splash'); $rootScope.$apply(); expect($state.current.name).toBe('splash'); }));
Sei que isso é um pouco fora do assunto, mas eu vim do Google procurando uma maneira simples de testar o modelo, o controlador e o URL de uma rota.
$state.get('stateName')
Darei à você
{ url: '...', templateUrl: '...', controller: '...', name: 'stateName', resolve: { foo: function () {} } }
em seus testes.
Então, seus testes podem ser parecidos com isto:
var state; beforeEach(inject(function ($state) { state = $state.get('otherwise'); })); it('matches a wild card', function () { expect(state.url).toEqual('/path/to/page'); }); it('renders the 404 page', function () { expect(state.templateUrl).toEqual('views/errors/404.html'); }); it('uses the right controller', function () { expect(state.controller).toEqual(...); }); it('resolves the right thing', function () { expect(state.resolve.foo()).toEqual(...); }); // etc
Para um state
que sem resolve
:
// TEST DESCRIPTION describe('UI ROUTER', function () { // TEST SPECIFICATION it('should go to the state', function () { module('app'); inject(function ($rootScope, $state, $templateCache) { // When you transition to the state with $state, UI-ROUTER // will look for the 'templateUrl' mentioned in the state's // configuration, so supply those templateUrls with templateCache $templateCache.put('app/templates/someTemplate.html'); // Now GO to the state. $state.go('someState'); // Run a digest cycle to update the $state object // you can also run it with $state.$digest(); $state.$apply(); // TEST EXPECTATION expect($state.current.name) .toBe('someState'); }); }); });
NOTA:-
Para um estado nested, talvez seja necessário fornecer mais de um modelo. Por ex. se tivermos um estado nested core.public.home
e cada state
, ie core
, core.public
e core.public.home
tiver um templateUrl
definido, teremos que adicionar $templateCache.put()
para a chave templateUrl
cada estado: –
$templateCache.put('app/templates/template1.html'); $templateCache.put('app/templates/template2.html'); $templateCache.put('app/templates/template3.html');
Espero que isto ajude. Boa sorte.
Você pode usar $state.$current.locals.globals
para acessar todos os valores resolvidos (veja o trecho de código).
// Given $httpBackend .expectGET('/api/users/123') .respond(200, { id: 1, email: 'test@email.com'); // When $state.go('users.show', { id: 123 }); $httpBackend.flush(); // Then var user = $state.$current.locals.globals['user'] expact(user).to.have.property('id', 123); expact(user).to.have.property('email', 'test@email.com');
Se você não está interessado em nada no conteúdo do template, você pode simplesmente zombar de $ templateCache:
beforeEach(inject(function($templateCache) { spyOn($templateCache,'get').and.returnValue(''); }