我在我的 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();
    });

});

每当我运行测试时,第一个测试通过但第二个测试产生错误:
Error: Unexpected request: 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();

09-15 17:51