我得到"超过2000毫秒的超时。确保在此测试中调用done()回调。"单元测试服务调用,响应承诺。我期待被拒绝的承诺。
UNIT TEST - 在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);
我已经读过其他堆栈溢出答案,非成功。
有什么想法吗?
我很感激帮助。
谢谢,
答案 0 :(得分: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();
});
});