我编写了一个使用API处理数据的服务。我已完成success response
单元测试,但面临404 Error Response
单元测试的问题。
请根据问题用真实场景更新答案。我已经有很少的教程,但是没有帮助。
这是我的服务代码:
angular.module('myApp').service('SizingService',
function (SizerGatewayApi, RestDomains, $q, UnitySizerService) {
let api = new SizerGatewayApi(GatewayUrl);
return {
postSizingResults: postSizingResults
};
function postSizingResults(unitySizerDTO) {
let deferred = $q.defer();
function handleSuccessResponse(data) {
deferred.resolve(data);
UnitySizerService.resultSummary = data;
}
function handleErrorResponse(response) {
//Not able to cover UT for 404
if (response.status === 404) {
deferred.resolve(response.body);
} else {
deferred.reject(response);
}
}
api.post({dto: unitySizerDTO}).then(handleSuccessResponse, handleErrorResponse);
return deferred.promise;
}
}
);
这是我的spec文件
describe('SizingService', function () {
beforeEach(module('basic-unity-replication-sizer-ui'));
let data = {
// response data
};
let SizerGatewayApiStub;
let unitySizerDTO = {
//post dto
};
let rootScope;
let $scope;
let SizingService;
let $q;
beforeEach(function () {
module(function ($provide) {
SizerGatewayApiStub = function () {
this.post = function (value) {
let deferred = $q.defer();
if (value.dto !== 'failure') {
deferred.resolve({data: data});
} else {
deferred.reject("no data");
}
return deferred.promise;
};
};
$provide.value('SizerGatewayApi', SizerGatewayApiStub);
});
inject(function (_$q_, $rootScope, _SizingService_) {
$q = _$q_;
rootScope = $rootScope;
$scope = $rootScope.$new();
SizingService = _SizingService_;
});
});
describe('should handle response', function () {
it('success', inject(function (SizingService) {
SizingService.postSizingResults(unitySizerDTO);
$scope.$apply();
expect(data).toBeDefined();
expect(data).not.toBeNull();
}));
//404 Failure scenarios needs to be covered by UT
it('failure', inject(function (SizingService) {
SizingService.postSizingResults(postWrongDTO);
$scope.$apply();
}));
});
});
答案 0 :(得分:1)
我实际上很难理解你的代码,但我想“你想要做的”是对SizerGateWayApiStub.post进行间谍并返回被拒绝的承诺。
这样的事情会让你走上正确的道路:
添加变量let postDeferred;
然后在您的beforeEach注射中,您将需要设置间谍
postDeferred = $q.defer();
spyOn(SizerGatewayApiStub, 'post').and.returnValue(postDeferred.promise);
然后在你的测试中你会做这样的事情
it('failure', inject(function (SizingService) {
let mockResponse = {
status = "404",
body = "somevalue"
};
let result = SizingService.postSizingResults(postWrongDTO);
postDeferred.reject(mockResponse);
$scope.$apply();
expect(SizerGatewayApiStub.post).toHaveBeenCalled();
expect(result).toEqual(mockResponse.body);
}));
});