Search code examples
angularjasminekarma-runnercode-coveragekarma-coverage

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:

59.09% Statements 13/22 37.5% Branches 3/8 42.86% Functions 3/7 52.63% Lines 10/19

What's the best methods to test these private tests, or at least, ignore them in code coverage?


Solution

  • 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.