gpt4 book ai didi

angularjs - 为什么我收到错误...意外请求 : GET/internalapi/quotes

转载 作者:行者123 更新时间:2023-12-03 05:52:07 26 4
gpt4 key购买 nike

我在我的 Angular 应用程序中定义了以下服务:

services.factory('MyService', ['Restangular', function (Restangular) {
return {
events : { loading : true },

retrieveQuotes : function() {
return Restangular.all('quotes').getList().then(function() {
return { hello: 'World' };
});
}
};
}]);

我正在编写以下规范来测试它:

describe("MyService", function () {

beforeEach(module('MyApp'));
beforeEach(module("restangular"));

var $httpBackend, Restangular, ms;

beforeEach(inject(function (_$httpBackend_, _Restangular_, MyService) {
ms = MyService;
$httpBackend = _$httpBackend_;
Restangular = _Restangular_;
}));


it("retrieveQuotes should be defined", function () {
expect(ms.retrieveQuotes).toBeDefined();
});

it("retrieveQuotes should return array of quotes", function () {

$httpBackend.whenGET("internalapi/quotes").respond({ hello: 'World' });
ms.retrieveQuotes();
$httpBackend.flush();
});

});

每当我运行测试时,第一个测试就会通过,但第二个测试会产生错误:

错误:意外请求:GET/internalapi/quotes

我做错了什么?

编辑:

结果我像这样配置了 Restangular ... RestangularProvider.setBaseUrl("/internalapi");。但我伪造了对 internalapi/quotes 的调用。注意缺少“/”。一旦我添加了斜杠 /internalapi/quotes 一切都很好:)

最佳答案

您需要告诉 $httpBackend 期待 GET 请求。

describe("MyService", function () {

beforeEach(module('MyApp'));
beforeEach(module("restangular"));

var Restangular, ms;

beforeEach(inject(function (_Restangular_, MyService) {
ms = MyService;

Restangular = _Restangular_;
}));


it("retrieveQuotes should be defined", function () {
expect(ms.retrieveQuotes).toBeDefined();
});

it("retrieveQuotes should return array of quotes", inject(function ($httpBackend) {

$httpBackend.whenGET("internalapi/quotes").respond({ hello: 'World' });

//expect a get request to "internalapi/quotes"
$httpBackend.expectGET("internalapi/quotes");

ms.retrieveQuotes();
$httpBackend.flush();
}));

});

或者,您可以将 respond() 放在 expectGET() 上。我更喜欢将 whenGET() 语句放在 beforeEach() 中,这样我就不必在每个测试中定义响应。

        //expect a get request to "internalapi/quotes"
$httpBackend.expectGET("internalapi/quotes").respond({ hello: 'World' });

ms.retrieveQuotes();
$httpBackend.flush();

关于angularjs - 为什么我收到错误...意外请求 : GET/internalapi/quotes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18147606/

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