角UI路由器单元测试(州到URL) [英] Angular ui router unit testing (states to urls)
问题描述
我有一些麻烦单元在我的应用程序,它是建立在角UI路由器上测试路由器。我想测试状态转换是否更改URL适当地(将有更多复杂的测试后,但是这就是我开始。)
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.)
下面是我的应用程序code的相关部分:
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"
})
})
和测试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");
})
})
#2类似的问题(与官方UI路由器测试code)建议包裹$ state.go调用$申请应该够了。但是,我已经做了,国家仍然没有更新。 $ state.current.name保持为空。
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.
推荐答案
一直有这个问题为好,终于想通了如何做到这一点。
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();
}]
}
});
}]);
单元测试下面将覆盖测试URL瓦特/参数,可以和执行其注入自己的依赖的决定:
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');
});
});
这篇关于角UI路由器单元测试(州到URL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!