单元测试——如何为$http编写一个karma-jasmine测试用例.进入angularJS



我有一个服务:

(function () {
    angular.module('app').service('MyAppService', MyAppService);
    MyAppService.$inject = ['$http', 'testUrl'];
    function MyAppService($http, testUrl) {
        var service = {
            testFunction: testFunction        
        };
        return service;
        function testFunction() {
            /*testurl is my backend API*/
            return $http.get(testUrl)                
                .error(function(){
                    return;
                })
                .then(function (response) {
                    return response.data;
                });
        }
    }
})();

我在控制器中调用它为:

        testControllerFunction();
        function testControllerFunction() {
             MyAppService.testFunction().then(function (response) {
                app.testResponse = response;  //This my http response
                console.log(app.testResponse);
            });
        }

我正在为成功的$http编写一个因果报应测试用例。在MyAppService中获取请求

describe('MyAppService', function () {
        var MyAppService,http;
        beforeEach(function() {
            module('app');
            inject(function ($injector) {
                MyAppService = $injector.get('MyAppService');
                testUrl = $injector.get('testUrl');
                http = $injector.get('$httpBackend');
            });
        });
        it('should call the backend testurl ', function () {
            MyAppService.testFunction();
            http.expectGET(testUrl);
        });
    });

但这似乎不起作用?我哪里做错了?谢谢!

您必须冲洗$httpBackend

    it('should call the backend testurl ', function () {
        http.expectGET(testUrl);            
        MyAppService.testFunction();
        http.flush();           
    });

相关内容