gpt4 book ai didi

testing - 测试取消$http请求时,$httpBackend.flush();抛出 "no pending request to flush"

转载 作者:行者123 更新时间:2023-11-28 20:04:52 27 4
gpt4 key购买 nike

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

谢谢,亚历山大

最佳答案

不是调用 $httpBackend.flush(),而是调用 $rootScope.$digest()。这将强制调用任何异步操作(例如 promises),然后由于请求被取消,因此不会刷新任何 http 请求。我没有针对此处给出的代码示例对此进行测试,但它适用于我的情况。

关于testing - 测试取消$http请求时,$httpBackend.flush();抛出 "no pending request to flush",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18144705/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com