我试图弄清楚如何在以下代码中测试403响应。代码按预期工作。我意识到使用403并不是最好的选择,但这是我现在无法控制的,我无法改变它。我是JS的新手测试,感觉我错过了一些东西并且已经达到了我的知识水平。任何帮助将不胜感激。
this.joinItem = function(item, joinOption) {
var deferred = $q.defer(),
joinUrl = ('http://testurl.com/company/items/abc456/join', joinData),
joinData = {
match: {
minid: joinOption['id']
}
};
$http.post(joinUrl, joinData, { headers: headers })
.success(handleJoinSuccess)
.error(handleJoinError);
function handleJoinSuccess() {
deferred.resolve({status: 204});
};
function handleJoinError(joinedResponse, status) {
var joinedItems = joinedResponse['joined_items'];
if (status === 403) {
deferred.resolve({
joinedItems: joinedItems,
status: status
});
} else {
deferred.reject({
status: status
});
}
}
return deferred.promise;
};
这是我到目前为止的测试。我不知道如何解决这个承诺。我可能在这个测试中有更多的废话而不是需要但我现在迷失了我不知道。
describe('itemService', function () {
'use strict';
var subject;
beforeEach(inject(function (_itemService_) {
subject = _itemService_;
}));
describe('#joinItem 403', function () {
var $httpBackend,
$rootScope,
deferred,
item,
joinOption,
joinData,
joinedResponse,
joinRequest,
joinedItemsResults,
joinedItems;
beforeEach(inject(function(_$httpBackend_, $q, _$rootScope_) {
$httpBackend = _$httpBackend_;
$rootScope = _$rootScope_;
deferred = $q.defer();
item = { id: 'abc456' };
joinOption = { id: 'optID' };
joinData = { match: { minid: 'optID' } };
joinedResponse = { 'joined_products': []};
joinRequest = $httpBackend.whenPOST('http://testurl.com/company/items/abc456/join', joinData).respond(403);
joinedItemsResults = { joined_products: [], status: 403 };
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('when request completes with 403 status', function () {
it('resolves the promise', function () {
var handler = jasmine.createSpy('error');
var promise = subject
.joinItem(item, joinOption);
promise.then(handler);
deferred.resolve(joinedResponse);
$rootScope.$digest();
$httpBackend.flush();
expect(promise).toBeResolvedWith(joinedItemsResults);
});
});
答案 0 :(得分:1)
我为您的问题设置了jsfiddle。在测试中,我简化了你的POST网址。 值得注意的事情:
您应该在expectPOST
$httpBackend
时返回数据响应(因为您在实际服务中执行此操作)。例如:
$httpBackend.whenPOST('/path/to/your/url')
.respond(403, yourErrorResponseData);
由于$http
已经返回承诺,因此您无需返回defer.promise
在测试中,您可以使用promise测试在$ httpBackend中返回的数据。并且不要忘记致电$httpBackend.flush
来刷新请求。
myService.joinItem(item, joinOption).then(function (data) {
expect(data).toEqual(joinedItemResults);
});
$httpBackend.flush();