angularjs - 如何在 angularJS 中为 $http.get 编写 karma-jasmine 测试用例?

标签 angularjs unit-testing http service karma-jasmine

我有一个服务:

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

我在我的 Controller 中称它为:

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

我正在为 MyAppService 中成功的 $http.get 请求编写 karma 测试用例:

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);
        });
    });

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

最佳答案

你必须 flush $httpBackend

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

关于angularjs - 如何在 angularJS 中为 $http.get 编写 karma-jasmine 测试用例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31283730/

相关文章:

javascript - $state.go() 不路由到其他状态,url 中的 #/null

c# - 从 Razor (asp.net) 迁移到 Angular JS 作为模板引擎

perl - 用于 Perl 单元测试的模拟文件系统

java - Intellij 中的路径对比。 eclipse

ruby-on-rails - ruby http 响应脚本发送大量 gzip 压缩内容

html - 将特定于选项卡的数据绑定(bind)到 HTTP GET 请求

angularjs - 使用 TypeScript 接口(interface)获取类型信息的 angular.service 的目的是什么

html - 设置元素位置时禁用链接

unit-testing - 我应该在单元测试时模拟所有依赖项吗?

http - AWS elasticbeanstalk-access_log 中的神秘 Http 408 错误