Testing async functions which use await Karma+Jasmine JS

31 views Asked by At

Im trying to test a async function using Karma and Jasmine in an angularjs v1.5.0 project. This async function (a) has 2 await like so:

async function a(){
    let var1 = await b()
    console.log(var1)
    let var2 = await c()
}

function b(){
    return $http.get(url1).then(
        function(response){
            ...
        }
    )
}

function c(){
    return $http.get(url2).then(
        function(response){
            ...
        }
    )
}

My test:

it('testA', inject(async function($httpBackend) {
    $httpBackend.when('GET','url1').respond(200, [myresult])
    $httpBackend.when('GET','url2').respond(200, [myresult])
    MyController().a()
    $httpBackend.flush();
}));

The problem is that $httpBackend.flush(); is only 'flushing' the first await and then the execution of the function 'a' does not continue, it can't even reach the console.log(var1). Can anybody help me with this?

I can't change the code, i just want to make a test for that code.

I tried to do await a() in the test, but that just doesnt work, it doesn't event resolve the first await.

1

There are 1 answers

1
Naren Murali On

Maybe try the below code, got it from this answer

it('testA', inject(async function($httpBackend) {
    $httpBackend.when('GET','url1').respond(200, [myresult])
    $httpBackend.when('GET','url2').respond(200, [myresult])
    MyController().a()
    try {
        httpBackend.flush();
    } catch (e) { } 
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
}));