【问题标题】:How to test $http without mock with jasmine and angular-mocks?如何在没有茉莉花和角模拟的情况下测试 $http?
【发布时间】:2015-07-22 08:42:52
【问题描述】:

我想通过对我的服务器的真实调用进行集成测试,所以,我不想使用 angular-mocks 中的 $httpBackend 模块,所以我试试这个:

beforeEach(inject(function($rootScope,_MembersDataSvc_){
    service = _MembersDataSvc_;
}));

it('test',function(done){
    service.me().then(function(){done();});
});

服务是:

function me() {
      return $http
        .get('urlBase/me')
        .then(meSuccess);

        function meSuccess(response) {
            return response.data.members[0];
        }
    }

这从不调用 $http,似乎 angular-mocks 覆盖了 $http 服务并且从未调用过。

一些想法?

编辑 1:

据此贴:http://base2.io/2013/10/29/conditionally-mock-http-backend/

你可以为你不想模拟的 $http 调用做一个 passThrough,所以你试试这个:

var service;
    var scope;
    var $httpBackend;

    beforeEach(inject(function($rootScope,_MembersDataSvc_,_$httpBackend_){
        service = _MembersDataSvc_;
        scope = $rootScope.$new();
        $httpBackend = _$httpBackend_;
    }));

it('test',function(done){
        //this.timeout(10000);
        $httpBackend.whenGET(/views\/\w+.*/).passThrough();
        $httpBackend.whenGET(/^\w+.*/).passThrough();
        $httpBackend.whenPOST(/^\w+.*/).passThrough();
        service.me().then(function(response){console.log(response);done();});
        scope.$apply();
        //service.getDevices(member).then(function(response){console.log(response);done();})
    });

但是这里的 passThrough 是未定义的。

编辑 2:

我读了这篇文章:http://blog.xebia.com/2014/03/08/angularjs-e2e-testing-using-ngmocke2e/,但我想那是一个独立的测试??,我想用 karma 和 jasmine 运行。

这是我的全部测试。

describe('integration test', function () {

    beforeEach(function () {
        module('MyAngularApp');
    });

    var service;
    var scope;
    var $httpBackend;

    beforeEach(inject(function($rootScope,_MembersDataSvc_,_$httpBackend_){
        service = _MembersDataSvc_;
        scope = $rootScope.$new();
        $httpBackend = _$httpBackend_;
    }));

    it('test for test',function(done){
        $httpBackend.whenGET(/views\/\w+.*/).passThrough();
        $httpBackend.whenGET(/^\w+.*/).passThrough();
        $httpBackend.whenPOST(/^\w+.*/).passThrough();
        service.me().then(function(response){console.log(response);done();});
        scope.$apply();
    });
});

【问题讨论】:

标签: angularjs jasmine angularjs-http


【解决方案1】:

我推荐使用 ngMidwayTester,它允许您连接到真正的后端,我用它在代码级别进行集成测试 - 所以介于单元测试和 e2e 测试之间:

Two types of tests in AngularJS (plus one more) - Full-Spectrum Testing with AngularJS and Karma

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2020-08-19
    • 2015-08-25
    • 1970-01-01
    相关资源
    最近更新 更多