为什么我收到错误...意外请求:GET/internalapi/quotes [英] Why do I receive error ... unexpected request: GET /internalapi/quotes
问题描述
我在我的 angular 应用中定义了以下服务:
I've defined the following service in my angular app :
services.factory('MyService', ['Restangular', function (Restangular) {
return {
events : { loading : true },
retrieveQuotes : function() {
return Restangular.all('quotes').getList().then(function() {
return { hello: 'World' };
});
}
};
}]);
我正在编写以下规范来测试它:
and I'm writing the following spec to test it :
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();
});
});
每当我运行测试时,第一个测试通过但第二个测试产生错误:
Whenever I run the tests, the first test passes but the second test produces the error :
错误:意外请求:GET/internalapi/quotes
我做错了什么?
结果我像这样配置了 Restangular
... RestangularProvider.setBaseUrl("/internalapi");
.但我在伪造对 internalapi/quotes
的调用.注意缺少/".一旦我添加了斜线 /internalapi/quotes
一切都很好:)
It turned out I'd configured Restangular
like so ... RestangularProvider.setBaseUrl("/internalapi");
. But I was faking calls to internalapi/quotes
. Notice the lack of the "/". Once I added the slash /internalapi/quotes
all was good :)
推荐答案
你需要告诉 $httpBackend 期待一个 GET 请求.
You need to tell $httpBackend to expect a GET request.
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()
中,这样我就不必在每个测试中定义响应.
Alternatively you can put your respond()
on your expectGET()
. I prefer to put my whenGET()
statements in a beforeEach()
that way I do not have to define the response within every test.
//expect a get request to "internalapi/quotes"
$httpBackend.expectGET("internalapi/quotes").respond({ hello: 'World' });
ms.retrieveQuotes();
$httpBackend.flush();
这篇关于为什么我收到错误...意外请求:GET/internalapi/quotes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!