Search code examples
angulartypescriptunit-testingjasminekarma-coverage

else path not taken in unit testing


I am working on angular 6

I don't have any else statement in my below code.But I am unable to cover branches due to else path not taken .What I need to do to get 100% branch coverage in this case?

 getHeaderDocumentList(documents: any) {
            if (documents) {
                documents.result.docAttachment.forEach(element => {
                    this.headerdocumentdetails.push(element.DocumentUniqueID);
                });
            }
        }

Solution

  • In order to get full coverage reported, the code needs to eventually hit the (here non-explicitly-existent) else-path. For that matter pass in a falsy parameter like 0 | false | undefined | null | NaN | '' | "" | `` as in

    component.getHeaderDocumentList(false);
    expect(false).toEqual(false); // This line is optional. Most test suites require some kind of assertion in each test.
    

    Now your test-suite should report both branches as covered.

    Last solution would be to add /* istanbul ignore else */ in before the if case. That will tell the coverage reporter to effectively ignore the else path