In this quick tutorial, you’ll learn how to unit test private methods while writing test cases for Angular.

Writing unit test for private methods and public methods is similar. But since you are unit testing an instance of an Angular component, you won’t be able to access the private method.

Let’s take a look at the following Angular component code :

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 constructor(){}

 private fun(){
   return "hello"
 }
}

You can access the above private method fun as shown:

it(`should return message 'hello'`, () => {
  const fixture = TestBed.createComponent(AppComponent);
  const app = fixture.componentInstance;
  expect(app['fun']()).toEqual('hello');
});