如果在 angularJS 的配置中配置,则测试 stateProvider 状态在 $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
});
});
但是我无法在配置中获取状态以显示在 $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"
推荐答案
首先,你不需要这个
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
中定义的,只需将您的 module
行更改为
Say your app
state is defined in myAppModule
, simply change your module
line to
beforeEach(module('myAppModule', 'myModule'));
<小时>
如果您不想包含具有 app
状态的模块,请在您的模块之前 包含一个配置函数,该函数会创建一个假父状态.为此,您将需要包含 ui.router
.
If you don't want to include the module with the app
state, include a config function before your module that creates a fake parent state. For this, you will need to include 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));
});
这篇关于如果在 angularJS 的配置中配置,则测试 stateProvider 状态在 $state 上返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!