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

时间:2013-08-09 13:20:32

标签: angularjs restangular

我已经在我的角应用中定义了以下服务:

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,一切都很好:)

2 个答案:

答案 0 :(得分:55)

您需要告诉$ 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(); 

答案 1 :(得分:17)

我遇到了和你们一样的问题。我的解决方案是在.expectGET的URL参数的开头添加一个'/'。使用您的示例:

$httpBackend.expectGET("/internalapi/quotes").respond({ hello: 'world'})

祝你好运