单元测试中未采用 else 路径

Ram*_*ran 10 unit-testing jasmine typescript karma-coverage angular

我正在研究角度 6

我在下面的代码中没有任何 else 语句。但是由于没有采用 else 路径,我无法覆盖分支。在这种情况下,我需要做什么才能获得 100% 的分支覆盖率?

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

Phi*_*ner 16

为了获得完整的覆盖率报告,代码最终需要到达(此处为非显式存在的)else-path。对于这个问题传递一个falsy参数一样0 | false | undefined | null | NaN | '' | "" | ``,如

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

现在您的测试套件应该报告两个分支都已覆盖。

最后的解决方案是/* istanbul ignore else */在 if 案例之前添加。这将告诉报道记者有效地忽略 else 路径

  • 最后的解决方案是在 if 情况之前添加 `/* istanbulignore else */` 。这将告诉报道记者有效地忽略 else 路径。 (8认同)

Ash*_*war 5

只需在没有部分的语句/* istanbul ignore else */之前添加即可。覆盖记者将忽略 else 路径。ifelse