如果在 $state 上的 angularJS returns null 配置中配置,则测试 stateProvider 状态

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>'
    });
}]);

和像这样使用 jasmine 的单元测试:

'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()

返回的数组中

我也检查过,包含配置的文件已加载并且就在那里。 谁能说我做错了什么?基本上我只想测试我期望的状态是否存在于 "myModule"

的配置中

首先,你不需要这个

beforeEach(module('ui.router'));

因为您的模块已经将其列为依赖项。

我的猜测是,您没有引入父 app 状态,因此不会创建您的 app.home 状态。

假设您的 app 状态在 myAppModule 中定义,只需将您的 module 行更改为

beforeEach(module('myAppModule', 'myModule'));

如果您不想包含具有 app 状态的模块,请在您的模块 之前 添加一个配置函数来创建一个假的父状态。为此,您 需要包括ui.router.

beforeEach(module('ui.router', function($stateProvider) {
    $stateProvider.state('app', { abstract: true });
}, 'myModule'));

或者,您可以监视 $stateProvider.state 并使用 expect 来确保它是通过 app.home 调用的,例如

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));
});