gpt4 book ai didi

javascript - Jasmine:如何测试 GET 请求中是否调用了正确的 URL

转载 作者:行者123 更新时间:2023-12-02 14:10:46 25 4
gpt4 key购买 nike

我想测试一项服务的功能。但是,我不知道如何模拟该服务中每个函数内使用的服务函数。我想检查是否调用了正确的 URL。

这是我的服务:

angular.module("myModule").service('myService', MyService);

MyService.$inject = ['$http'];

function MyService($http) {
var myService = this;

myService.request = function (reqType, url, headers, requestBody, fnc, fncFail) {
$http(createRequest(reqType, point, headers, requestBody)).then(function (response) {
if (typeof fnc == 'function') {
fnc(response.data);
}
}, function (response) {
if (typeof fncFail == 'function') {
fncFail(response);
}
});
};

myService.getInfo = function (id, fnc, fncFail) {
myService.request("GET", "myURL", {"Accept":"application/json"}, null, function (data) {
fnc(data);
}, fncFail);
};

现在是我的测试套件的片段:

beforeEach(inject(function ($injector) {
service = $injector.get("myService");
httpBackend = $injector.get("$httpBackend");
http = $injector.get("$http");
}));

it("function getInfo is called with the correct URL", function () {
spyOn(http, 'get').and.callThrough();
myService.getInfo(id, fnc, fncFail);
expect(http.get).toHaveBeenCalledWith("myurl");
httpBackend.flush();
});

我不确定这是否是测试我的方法“getInfo”的正确方法,因为它调用其他服务函数(“请求”)。

最佳答案

使用 $httpBackend 来期待 XHR 调用。使用以下 afterEach block ,如果未进行调用,测试将失败。

afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});

it("function getInfo is called with the correct URL", function () {
httpBackend.expect('GET', "myurl").respond(200, {mocked: "response"});
myService.getInfo(id, fnc, fncFail);
httpBackend.flush();
});

关于javascript - Jasmine:如何测试 GET 请求中是否调用了正确的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39597129/

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