测试stateProvider状态,如果在angularJS中的config中配置,则在$ state上返回null [英] Testing stateProvider state if configured in config in angularJS returns null on $state
问题描述
我有这样的配置:
angular.module('myModule', ['ui.router'])
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('app.home', {
abstract: true,
url: '/home',
template: '<div>Foo Bar</div>'
});
}]);
以及使用茉莉花的单位测试:
and a unit test using jasmine like this:
'use strict';
describe('Module: myModule', function() {
var $rootScope, $state;
beforeEach(module('ui.router'));
beforeEach(module('myModule'));
beforeEach(inject(function(_$rootScope_, _$state_) {
$state = _$state_;
$rootScope = _$rootScope_;
}));
it('must have a route state for home', function(){
console.log($state.get('app.home')); // this returns null
});
});
但是我无法让配置中的状态显示在<$ c返回的数组上$ c> $ state.get()
However I could not get the state in the config to show up on the array returned by $state.get()
我还检查了包含配置的文件,它就在那里。
谁能说我做错了什么?基本上我只想测试我期望的状态是否存在于myModule的配置中
I also checked and the file containing the config is loaded and it is there. Can anyone say what I am doing wrong? Basically I just want to test if the states I am expecting are existing in the config of "myModule"
推荐答案
首先,你要不要不需要这个
First, you don't need this
beforeEach(module('ui.router'));
因为您的模块已将其列为依赖项。
as your module lists it as a dependency already.
我的猜测是,您没有引入父 app
状态,因此您的 app.home
州将不会被创建。
My guess is, you aren't bringing in the parent app
state so your app.home
state will not be created.
假设你的 app
状态在 myAppModule $中定义c $ c>,只需将
模块
行更改为
Say your app
state is defined in myAppModule
, simply change your module
line to
beforeEach(module('myAppModule', 'myModule'));
如果您不想包含模块使用 app
状态,在模块中包含一个配置函数,以创建一个假父状态。为此,将需要包含 ui.router
。
beforeEach(module('ui.router', function($stateProvider) {
$stateProvider.state('app', { abstract: true });
}, 'myModule'));
或者,你可以监视 $ stateProvider.state
并使用 expect
确保使用 app.home
调用它,例如
Alternatively, you could spy on $stateProvider.state
and use an expect
to ensure it was called with app.home
, eg
var $stateProvider;
beforeEach(module('ui.router', function(_$stateProvider_) {
$stateProvider = _$stateProvider_;
spyOn($stateProvider, 'state');
}, 'myModule'));
it('must have a route state for home', function() {
expect($stateProvider.state).toHaveBeenCalledWith('app.home', jasmine.any(Object));
});
这篇关于测试stateProvider状态,如果在angularJS中的config中配置,则在$ state上返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!