【问题标题】:Testing stateProvider state if configured in config in angularJS returns null on $state如果在 angularJS 的配置中配置,则测试 stateProvider 状态在 $state 上返回 null
【发布时间】:2015-05-19 12:24:51
【问题描述】:

我有一个这样的配置:

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”的配置中

【问题讨论】:

    标签: javascript angularjs unit-testing angular-ui-router


    【解决方案1】:

    首先,你不需要这个

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

    【讨论】:

    • 是的,添加父状态“app”似乎确实可以解决问题。但是,将另一个模块添加为依赖项对我来说不起作用。如果可能的话,我怎么能只在单元测试中模拟父状态?
    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    相关资源
    最近更新 更多