我在我的服务中实现了取消 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,我如何测试该请求是否被取消。
谢谢你,亚历山大