javascript - 如果在 angularJS 的配置中配置,则测试 stateProvider 状态在 $state 上返回 null

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

我有这样一个配置:

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

关于javascript - 如果在 angularJS 的配置中配置,则测试 stateProvider 状态在 $state 上返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30316334/

相关文章:

angularjs - Angular 翻译更新翻译表

css - 多个 Bootstrap 选项卡 - 垂直和水平

angularjs - Angular JS 范围不从包含的模板更新

python - 路径不能包含斜杠

c# - 如何在不依赖注入(inject)的情况下模拟我们正在 C# 中测试的同一类的另一个方法

javascript - JSLint - 如何修复 ActiveXObject 在定义之前使用的错误

Javascript/jQuery scrollTop 滚动时上下跳动

javascript - 使用 python 或 javascript 将 Hershey 字体 .jhf 解析为 json

javascript - 使用 sequelize 根据 express.js 中的路由更改数据库连接

unit-testing - Jest 单元测试问题 : "module not found"