4

我收到“超过 2000 毫秒的超时。确保在此测试中调用了 done() 回调。” 在对一个返回承诺的服务调用进行单元测试时。我期待一个被拒绝的承诺。

单元测试- 在 PhantomJS 上运行的 Karma-Mocha-Chai

describe('teamService', function () {

  var teamSrvc, q;

  beforeEach(angular.mock.module('scCommon'));

  beforeEach(angular.mock.inject(function ($q, teamService) {
    teamSrvc = teamService;
    q = $q;
  }));

  describe('getTeamsByNameStartWith', function () {

    it('should return reject promise when passing invalid text to search', function () {

      var invalidFirstArg = 132;
      var validSecondArg = 10;

      return teamSrvc.getTeamsByNameStartWith(invalidFirstArg, validSecondArg).then(
        function (result) {

        },
        function (err) {
          err.should.equal("Invalid text to search argument passed.");
        }
      );


    });

 });


});

以下是我正在测试的服务。我在运行站点时测试了 teamService,它确实成功地返回了一个被拒绝的承诺。

(function (ng) {

'use strict';

ng.module('scCommon')
.service('teamService', ['$q', '$http', function ($q, $http) {


  var getTeamsByNameStartWith = function (textToSearch, optLimit) {
    var defer = $q.defer();

    if (typeof textToSearch != "string") {
      defer.reject("Invalid text to search argument passed.");
      return defer.promise;

    } else if (typeof optLimit != "number") {
      defer.reject("Invalid limit option argument passed.");
      return defer.promise;
    }


    $http.get('url')
      .success(function (data) {
        defer.resolve(data);
      })
      .error(function () {
        defer.reject("There was an error retrieving the teams");
      });

    return defer.promise;
  };


  return {
     getTeamsByNameStartWith: getTeamsByNameStartWith
  }

}])

})(angular);

我已经阅读了其他堆栈溢出答案,但没有成功。

有任何想法吗?

我很感激帮助。

谢谢,

4

1 回答 1

2

一位朋友看了看,立即看到了这个问题。显然我需要做一个 rootScope.$apply。

describe('teamService', function () {



 var teamSrvc, q, rootScope;

  beforeEach(angular.mock.module('scCommon'));

  beforeEach(angular.mock.inject(function ($q, teamService, $rootScope) {
    teamSrvc = teamService;
    q = $q;
    rootScope = $rootScope;
  }));

  describe('getTeamsByNameStartWith', function () {

it('should return reject promise when passing invalid text to search', function () {

  var invalidFirstArg = 132;
  var validSecondArg = 10;

  teamSrvc.getTeamsByNameStartWith(invalidFirstArg, validSecondArg).then(
    function (result) {

    },
    function (err) {
      err.should.equal("Invalid text to search argument passed.");
    }
  );

  rootScope.$apply();

});

it('should return reject promise when passing invalid number to limit', function () {

  var validFirstArg = "alex";
  var invalidSecondArg = "10";

  teamSrvc.getTeamsByNameStartWith(validFirstArg, invalidSecondArg).then(
    function (result) {

    },
    function (err) {
      err.should.equal("Invalid limit option argument passed.");
    }
  );

  rootScope.$apply();

});

});

于 2015-09-19T16:00:57.343 回答