ui-router中的单元测试解决了回调

时间:2016-05-03 20:00:19

标签: angularjs angular-ui-router jasmine istanbul

我一直在一个项目中工作,并且我一直在使用ui-router插件。 当我检查代码的覆盖级别时,总是在resolve函数回调中,我的覆盖工具说我的测试从不执行resolve函数。

我的问题:

应该如何测试此代码?

代码示例:

$stateProvider
      .state('measures.users', {
        url: 'users',
        views: {
          'navbar': APP_SETTINGS.NAVBAR_SETTINGS,
          'main': {
            templateUrl: 'assets/views/users/users.html',
            controller: 'UsersController',
            controllerAs: 'users',
            resolve: {
              UsersResolve: ['UsersService', function(UsersService){

                  //My coverage tool never pass in here. 
                  //I need testing this area but i dont know what should be test
                  return UsersService.getUsers();
              }]
            }
          }
        }
      })

修改 最后,当我转换到州' measures.users'时,我测试我的服务是否已被调用。

describe('State check', function(){

    var state, rootScope, UsersService;

    beforeEach(module('exampleApp'));
    beforeEach(inject(eachSpecSetup));

    function eachSpecSetup($state, $rootScope, $controller,_UsersService_){
        state = $state;
        UsersService = _UsersService_;
        rootScope = $rootScope;
    }

    it('should be call a UsersService.getUsers to resolve the array to state users', spec1);

    function spec1(){

        spyOn(UsersService, 'getUsers');

        state.go('measures.users');
        rootScope.$digest();

        expect(UsersService.getUsers).toHaveBeenCalled();
    }

});

here

中的类似示例

1 个答案:

答案 0 :(得分:-1)

请确保:

  1. url'用户'在你的测试中涵盖;
  2. 在UsersController中,您已经调用了UsersResolve服务。
  3. resolve中可能存在一些语法错误:

    $stateProvider
      .state('measures.users', {
        url: 'users',
        views: {
          'navbar': APP_SETTINGS.NAVBAR_SETTINGS,
          'main': {
            templateUrl: 'assets/views/users/users.html',
            controller: 'UsersController',
            controllerAs: 'users',
            resolve: {
              UsersService: UsersServuce,
              UsersResolve: function(UsersService){
                  return UsersService.getUsers();
              }
            }
          }
        }
      })