gpt4 book ai didi

javascript - 使用 Angular 服务 + Jasmine 进行 uni 测试 404 故障响应

转载 作者:行者123 更新时间:2023-12-03 05:51:23 24 4
gpt4 key购买 nike

我编写了一个使用 API 处理数据的服务。我已经完成了相同的成功响应单元测试,但面临404错误响应单元测试的问题。

请根据问题用真实场景更新答案。我已经提供了一些教程,但这些没有帮助。

这是我的服务代码:

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;
}
}
);

这是我的规范文件

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();
}));
});

});

最佳答案

我实际上很难理解你的代码,但我“认为”你想要做的是在 SizerGateWayApiStub.post 上放置一个 spy 并返回被拒绝的 promise 。

这样的事情应该会让你走上正确的道路:

添加变量let postDeferred;

然后在 beforeEach 注入(inject)中,您需要设置 spy

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);
}));
});

关于javascript - 使用 Angular 服务 + Jasmine 进行 uni 测试 404 故障响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40140090/

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