使用仅http请求的angularjs对服务进行单元测试

使用仅http请求的angularjs对服务进行单元测试,angularjs,unit-testing,service,jasmine,Angularjs,Unit Testing,Service,Jasmine,我在服务中有一个名为getFrame的函数。该函数只向控制器返回$http调用 angular.module('app').factory('DemoFactory', function ($http) { function getFrame(id) { var url = 'http://localhost:8080/frames/' + id + '/'; return $http.get(url); } return {

我在服务中有一个名为getFrame的函数。该函数只向控制器返回$http调用

angular.module('app').factory('DemoFactory', function ($http) {
    function getFrame(id) {
        var url = 'http://localhost:8080/frames/' + id + '/';
        return $http.get(url);
    }

    return {
        getFrame: getFrame
    };
});
现在,我想为此编写unittest,具体操作如下:

describe('Service: DemoFactory', function () {

    // load the service's module
    beforeEach(module('app'));

    // Instantiate service
    var $httpBackend,
        DemoFactory;

    beforeEach(inject(function (_$httpBackend_, _DemoFactory_) {
        $httpBackend = _$httpBackend_;
        DemoFactory = _DemoFactory_;
    }));

    it('should send proper http request from getFrame', function () {
        $httpBackend.expectGET('http://localhost:8080/frames/1/').respond(200);
        DemoFactory.getFrame(1);
        $httpBackend.flush();
    });

    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });
});

对于给定的服务,我的目标是测试getFrame是否发出正确的http请求。所以我认为我在这里做得很好。但有件事让我怀疑,它并没有任何期待。因此,我需要确认,对于我编写的服务,我可以进行如上所述的单元测试。我是否需要在单元测试中进行其他操作,或者我可以以其他方式进行操作?

您使用httpBackend,但您没有模拟您的响应。读取httpBackend.when(…).response(…)附近的httpBackend文档。并将expect添加到响应结果中。我想我不需要使用httpBackend.when,只要我使用respond with httpBackend.expect