角度分辨率的测试方法

时间:2016-07-27 01:07:30

标签: javascript angularjs jasmine karma-jasmine angular-promise

我正在编写用于测试角度服务调用的测试用例。我在解析中返回一个变量值。我的问题是,在承诺解决后,我得到一个未定义的值作为响应。以下是我正在使用的代码。

        resolve: {
    peopleData: ($q, service, apiOperations, errorService) => {

      const getHelloWorld = () => {
        {
          return‘ hello - world ';
        }
      };

      const errorHandler = (error, operation) => {
        var deferred = $q.defer();
        errorService.handle(error, operation);
        deferred.resolve({});
        return deferred.promise;
      };

      service.getPeopleName().then((response) => {
        console.log('called then method');
        if (!angular.isUndefined(response)) {
          return response;
        } else {
          return {};
        }
      }).catch((error) => {
        errorHandler(error, apiOperations.GET_PEOPLE);
        return {};
      });

    }

现在我的测试用例是

describe('state peopleService application', function() {
  let $q, authService, $state, state_name = 'main.application',
    result, $rootScope, applicationService;
  let errorService = {
    handle: function(error, operation) {}
  };
  let apiOperations = {
    GET_People: ‘getPeople ',
    TEST_ERROR: 'testError'
  };

  angular.module('mock.Service', []).service('mockPeopleService', function() {
      var peopleService = {};
      peopleService.getPeople = function() {
        let deferred = $q.defer();
        deferred.resolve(‘dummy response ');
          return deferred.promise;
        }
        return applicationService;
      }); beforeEach(angular.mock.module(home)); beforeEach(angular.mock.module('mock.Service')); beforeEach(angular.mock.inject(function(_$q_, _$state_, _mockPeopleService_, _$rootScope_) {
      $q = _$q_;
      $state = _$state_;
      $rootScope = _$rootScope_;
      peopleService = _mockPeopleService_;
    })); it('should load the data', () => {
      let state = $state.get(state_name);
      let result = state.resolve.peopleData($q, peopleService, apiOperations, errorService);
      $rootScope.$apply();
      console.log('result  ' + result);

    });


  })
});

log.console返回结果未定义

1 个答案:

答案 0 :(得分:0)

请记住,在带有{花括号}的箭头函数中,return需要是显式的,就像常规函数一样。因此,对于目前编写的resolve.peopleData()undefined并不令人惊讶。

添加return并整理,您最终可能会遇到以下情况:

resolve: {
    peopleData: ($q, service, apiOperations, errorService) => {
        return service.getPeopleName().then(response => {
        ^^^^^^
            if (angular.isUndefined(response)) {
                throw new Error('response is undefined');
            }
            return response;
        }).catch(error => {
            errorService.handle(error, apiOperations.GET_PEOPLE);
            return {};
        });
    }
}

现在,测试至少有机会工作。