简体   繁体   English

使用 Angular 和 Jasmine/Karma 使用私有方法进行测试和代码覆盖

[英]Tests and code-coverage with private methods with Angular and Jasmine/Karma

So, I got these methods on my button component.所以,我在我的按钮组件上得到了这些方法。

export class SidebarButtonComponent implements OnInit {

  private subscribeToRouter(): void {
    this.router.events.subscribe(route => {
      if (route instanceof NavigationEnd) {
        this.isSelected(route.urlAfterRedirects);
      }
    });
  }

  private isSelected(route: string): void {
    if (this.checkRoute(route)) {
      this.selected = true;
    } else {
      this.selected = false;
    }
  }

  private checkRoute(route: string): boolean {
    return route.includes(this.link);
  }

}

I know I can't access private methods on my specs files, but the code coverage from Angular says I don't cover it:我知道我无法访问规范文件中的私有方法,但是 Angular 的代码覆盖率说我没有覆盖它:

59.09% Statements 13/22 37.5% Branches 3/8 42.86% Functions 3/7 52.63% Lines 10/19 59.09% 语句 13/22 37.5% 分支 3/8 42.86% 函数 3/7 52.63% 行 10/19

What's the best methods to test these private tests, or at least, ignore them in code coverage?测试这些私有测试的最佳方法是什么,或者至少在代码覆盖率中忽略它们?

Access modifiers in typescript are only used in compile time.打字稿中的访问修饰符仅在编译时使用。 You can't directly access them like this你不能像这样直接访问它们

component.privateMethod(); // not accessible 

But you can access them using any:但是您可以使用以下任何方式访问它们:

(component as any).privateMethod();

This is a workaround to access the private methods, otherwise you can test them using the methods in which these private methods are called.这是访问私有方法的一种变通方法,否则您可以使用调用这些私有方法的方法来测试它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 想要 karma 代码覆盖 html 而无需编写 --code-coverage - Want karma code coverage html without writing --code-coverage Angular 7,Jasmine代码覆盖率不包含函数,而测试返回正值 - Angular 7, Jasmine code-coverage does not include a function, while the test returns positive Angular:如何让私有方法进入代码覆盖范围? - Angular: How to Get Private Methods into Code Coverage? Karma Jasmine 具有可观察性,代码覆盖率未完全覆盖 - Karma Jasmine with observable, code coverage not fully coveraged 使用 Karma / Jasmine 进行 Angular 8 测试 -> 100% 代码覆盖率未涵盖在 Angular 路由中的 loadChildren - Angular 8 test with Karma / Jasmine -> 100% code coverage not covered for loadChildren in angular routes angular cli 排除`ng test --code-coverage`的文件/目录 - angular cli exclude files/directory for `ng test --code-coverage` 在WebStorm中使用Angular 2调试Karma / Jasmine测试 - Debugging Karma/Jasmine Tests with Angular 2 in WebStorm 使用Angular 4,Webpack 2,Karma和Jasmine获得单元测试范围 - Getting unit test coverage working with Angular 4, Webpack 2, Karma, and Jasmine 使用Karma,Angular和Husky执行代码覆盖 - Code Coverage Enforcement with Karma, Angular and Husky Angular 未生成业力代码覆盖率报告文件夹 - Angular karma code coverage report folder not generated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM