我在我的服务中实现了取消http请求,我想测试它:
angular.module('EmsWeb.Services').factory('DalService', ['$q', '$http', 'AppModel', 'DalRequestCache', function ($q, $http, appModel, dalRequestCache) {
return {
apiUrl: '../api/ModuleApi/',
viewUrl: '../',
submitRequestPromise: function (senderIdentifier, url, requestData) {
this.cancelRequest(senderIdentifier);
var canceler = $q.defer();
this.addToCache(senderIdentifier, canceler);
return $http({
method: 'POST',
url: url,
data: requestData?requestData:null,
timeout: canceler.promise
});
},
addToCache: function (senderIdentifier, canceler) {
var request = { 'senderIdentifier': senderIdentifier, 'cancelPromise': canceler };
dalRequestCache.put(senderIdentifier, request);
},
cancelRequest: function (senderIdentifier) {
var request = dalRequestCache.get(senderIdentifier);
if (request) {
request.cancelPromise.resolve('canceled');
dalRequestCache.remove(senderIdentifier);
return true;
}
return false;
},
getModules: function (senderIdentifier, appContext, successFn, errorFn) {
var url = this.apiUrl + 'GetModules';
var ctx = appModel.context.toRequestContext(appContext);
this.submitRequest(senderIdentifier, url, ctx, successFn, errorFn);
}
};
}]);
这是测试
describe("Unit: Testing Services", function() {
beforeEach(angular.mock.module('EmsWeb.Services'));
describe("Unit: DalService", function () {
var $httpBackend, dalService, appModel;
beforeEach(inject(function ($q, _$httpBackend_, AppModel, DalService) {
dalService = DalService;
appModel = AppModel;
$httpBackend = _$httpBackend_;
$httpBackend.when('POST', '../api/ModuleApi/GetModules').respond({ userId: 'userX', 'A-Token': 'xxx' });
appModel.context.company = { code: 'LPL' };
}));
describe("canceling requests", function () {
it('checks request should be canceled ', function () {
var returnedData;
var callBackFn = function (data) {
returnedData = data;
};
dalService.getModules('senderIdentifier', appModel.context, callBackFn, callBackFn);
var canceled = dalService.cancelRequest('senderIdentifier');
$httpBackend.flush();
expect(canceled).to.be.true;
expect(returnedData).to.undefined;
});
});
afterEach(function () {
$httpBackend.verifyNoOutstandingRequest();
});
});
当我运行它时,我收到“没有待处理的冲洗请求”错误。 如果我不调用flush,我该如何测试该请求被取消。
谢谢你, 亚历山大
答案 0 :(得分:4)
请致电$httpBackend.flush()
,而不是致电$rootScope.$digest()
。这将强制调用任何异步操作(例如promises),然后由于请求被取消,将不会刷新http请求。我没有对这里给出的代码示例进行测试,但它在我的情况下有效。