如何在不使用http后端的情况下对Http Get进行单元测试,我想嘲笑后端,我使用jasmine和Angular 1?

时间:2016-03-18 14:38:19

标签: angularjs unit-testing jasmine karma-jasmine

如何在不使用http后端的情况下对Http Get进行单元测试,我想模拟后端,而不是使用http后端进行真正的调用。

我使用Jasmine,Karma亚军与Angular版本1?

这是我当前的代码,但可以使用Http Backend:

describe('appService', function() {
    beforeEach(module('msApp.services'));
    beforeEach(module('msApp.environment'));

    var scope, appServiceMock, httpBackendMock, environment;

    describe('service tests', function() {
        beforeEach(inject(function($rootScope, $injector, Environment) {      
              scope = $rootScope.$new();    
              environment = Environment;

              //I want to mock the httpBackend bit here:
              httpBackendMock = $injector.get('$httpBackend');  
              appServiceMock = $injector.get('AppService');    
        }));

        afterEach(function() {
            httpBackendMock.verifyNoOutstandingExpectation();
            httpBackendMock.verifyNoOutstandingRequest();
        });          

        it('Test 1 - call login user', function() {  
            var user = {};

            spyOn(appServiceMock, 'loginUser');   

            appServiceMock.loginUser(user, jasmine.any(Function), jasmine.any(Function));

            expect(appServiceMock.loginUser).toHaveBeenCalledWith(user, jasmine.any(Function), jasmine.any(Function));
        });

        it("Test 2 - call http directly", function(){
            var taskId = 1;

            httpBackendMock.expectGET(environment.apiURL + 'Tasks/GetTask?sessionId='+ scope.session + "&taskId=" + taskId)
            .respond(200, data);

            function mockSuccessFunction(){return true;};

            appServiceMock.getTask(taskId, mockSuccessFunction, jasmine.any(Function));                                  

            httpBackendMock.flush(); 
        })              
    });
});

3 个答案:

答案 0 :(得分:2)

我无法记住细节,但我很久以前通过使用$ httpBackend做了这件事,但告诉它将调用传递给实际的互联网,如下所示:

$httpBackend.whenGET(/regex/).passThrough();

--- ---更新

我刚刚看到了我做过的代码。详情如下: http://www.bradoncode.com/blog/2015/06/16/unit-test-http-ngmock-passthrough/

答案 1 :(得分:0)

我在我的应用中使用了angular-resource.js来模拟后端。您只需要添加ngResource模块并为要模拟的端点调用$ resource(“api / url /:id”)。

答案 2 :(得分:0)

您可以提供模拟的$http,而不是获得实际的注入服务。

describe('appService', function() {
  beforeEach(module('msApp.services'));
  beforeEach(module('msApp.environment'));

  var $http, scope;

  describe('service tests', function() {
    beforeEach(inject(function($rootScope, $provide) {      
          scope = $rootScope.$new();    
          $http = jasmine.createSpyObj('$http', ['get']);
          $provide.value('$http', $http);    
    }));
    it('get data', function() {
     $http.get();
     expect($http.get).toHaveBeenCalled();
    });
  });
});