【问题标题】:Trouble testing state transition in ui-router在 ui-router 中测试状态转换时遇到问题
【发布时间】:2015-10-27 07:36:59
【问题描述】:

我正在尝试使用类似于https://stackoverflow.com/a/21078955/270511 建议的 ui-router 为 Angular 应用程序编写测试。

it('should transition to state', inject(function($rootScope, $state, $log) {
  $rootScope.$on('$stateChangeError', function(ev, toState, toParams, fromState, fromParams, error) {
    $log.error('$stateChangeError: ', error);
  });
  $rootScope.$on('$stateNotFound', function(ev, toState, toParams, fromState, fromParams, error) {
    $log.error('$stateNotFound: ', error);
  });

  var caseId = 1;
  $state.go('case.summary', { id: caseId }, { notify: true, reload: true });
  $rootScope.$digest();
  $log.debug('$state.current.name: ' + $state.current.name);
  expect($state.current.name).toEqual('case.summary');  // fails
  expect($state.is('case.summary', { id: caseId })).toBeTruthy(); // fails
}));

但是这个测试失败了。

summary section ✓ should respond to URL LOG LOG: 'debug: caseSvc.get, url: ,http://52.2.224.42:3000/cases/1' LOG LOG: 'debug: $state.current.name: ' ✗ should transition to state Expected '' to equal 'case.summary'.

不过,这个测试成功了:

it('should respond to URL', inject(function($state) {
  expect($state.href('case.summary', { id: 1 })).toEqual('#/cases/1/summary');
}));

目前正在尝试在 Chrome 调试器中跟踪这一点。

在这一点上我很困惑。

【问题讨论】:

  • case.summary 状态是否在进入状态之前解析任何数据? (或向我们展示您所在州的配置)

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


【解决方案1】:

$state.go() 返回一个需要等待的承诺。

代替

$state.go('case.summary', { id: caseId }, { notify: true, reload: true });
expect ...

我不得不写

  $state.go(stateName, { id: caseId }, { notify: true, reload: true })
  .then(function() {
    $rootScope.$digest();
    $log.debug('$state.current.name: ' + $state.current.name);
    expect($state.current.name).toEqual(stateName);
    expect($state.is(stateName, { id: caseId })).toBeTruthy();
  });

事实上,$state.go 的第三个参数也不是必须的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多