我在我的角度应用程序中定义了以下服务:
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(); }); });
每当我运行测试时,第一个测试通过,但第二个测试产生错误:
Error: Unexpected request: GET /internalapi/quotes
我究竟做错了什么?
编辑:
原来,我已经配置Restangular是这样的… RestangularProvider.setBaseUrl("/internalapi");。但是我在打电话给我internalapi/quotes。注意缺少“ /”。一旦我添加了斜线,/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()那种方式陈述我的陈述,而不必在每个测试中都定义响应。
respond()
expectGET()
whenGET()
beforeEach()
//expect a get request to "internalapi/quotes" $httpBackend.expectGET("internalapi/quotes").respond({ hello: 'World' }); ms.retrieveQuotes(); $httpBackend.flush();