else path not taken in unit testing
Asked Answered
F

2

15

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);
                });
            }
        }
Fortier answered 15/11, 2019 at 12:36 Comment(1)
Did you try passing an input that evaluates false to the if statement and bypasses it?Ainsworth
M
20

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

M16 answered 15/11, 2019 at 12:42 Comment(4)
Good Idea! But some case I am unable to fix this. Any way as of now 80% is enough. And one more question: did you heard anything about sourceMap:trueFortier
Hm,that is rather weird. It should stop complaining once you ran the tests again.M16
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.M16
If the expected output of a false/empty document list is that headerdocumentdetails does not change, that is a valid test.Elocution
J
5

Just add /* istanbul ignore else */ before if statement which do not have else part. Coverage reporter will ignore the else path.

Jarl answered 18/8, 2021 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.