测试Async $ http实际调用angularjs

时间:2015-08-10 23:01:42

标签: javascript angularjs angular-http karma-mocha

我想对angularjs服务进行e2e测试,而不需要模拟$ http调用。对fsSvc.getSubject的调用导致多个嵌入式异步调用,最终调用回调函数,我已将调用完成。

不确定这不起作用 - 如果没有嘲笑,$ http是否应该调用真实的电话?:

 it('should pass auth', function(done) {
        inject(function (fsSvc) {
            var cb = sinon.spy();
            stubs.updateRecord = sinon.stub(dataSvc, 'updateRecord');

            dataSvc.LO.famSrch.access_token_expires = false;

            fsSvc.getSubject("abc", function(err, data) {
                console.log("err:" + err);
                done();
                cb();
            });

            $timeout.flush();
            expect(dataSvc.LO.famSrch.discovery).to.not.be.undefined;
            expect(dataSvc.LO.famSrch.discovery.links).to.not.be.undefined;
            expect(dataSvc.LO.famSrch.access_token).to.not.be.undefined;
            expect(dataSvc.LO.famSrch.username).to.equal("test");
            expect(dataSvc.LO.famSrch.password).to.equal(btoa("test"));
            expect(dataSvc.LO.famSrch.access_token_expires).to.be.greaterThan(3600000);

            expect(stubs.updateRecord.callCount).to.equal(1);
            expect(stubs.updateRecord.args[0][1]).to.equal("localOption");
            expect(cb.callCount).to.equal(1);
        })
    });

1 个答案:

答案 0 :(得分:0)

我认为包含e2e没有任何问题。为什么这对你来说是一个问题?

如果您决定尝试使用ngMockE2E,请记住它不会处理异步/承诺响应。

例如,如果您的模拟响应是一个承诺,它将无法正常工作。转到数据库或使用诸如WebSQL / IndexedDB(或其他内存数据库)之类的实例将无法正常工作。

我开发了一个名为angular-mocks-async的角度插件来解决这个问题。这是一个模拟的例子:

var app = ng.module( 'mockApp', [
    'ngMockE2E',
    'ngMockE2EAsync'
]);

app.run( [ '$httpBackend', '$q', function( $httpBackend, $q ) {

    $httpBackend.whenAsync(
        'GET',
        new RegExp( 'http://api.example.com/user/.+$' )
    ).respond( function( method, url, data, config ) {

        var re = /.*\/user\/(\w+)/;
        var userId = parseInt(url.replace(re, '$1'), 10);

        var response = $q.defer();

        setTimeout( function() {

            var data = {
                userId: userId
            };
            response.resolve( [ 200, "mock response", data ] );

        }, 1000 );

        return response.promise;

    });

}]);
相关问题