how to write Angular12 unit test with Private method and local variables

Viewed 35
export interface UserDetails {
name: 'string',
id: 'string',
address: {
area: 'string',
city: 'string',
}}
export class UserComponent {
Private GetData() {
let userDetail: UserDetails = {
name: 'user name'
}
userDetail.address.city = 'city Name'; //(city name will dynamically add for example added manually)
} 
}

How access the local variable let userDetail to unit test .spec file.

1 Answers

Unfortunately you cannot test a local variable, because it only exists inside of the function, where it is defined.

A private function can be called and tested like this:

describe("UserComponent", () => {
 let component: UserComponent;
  beforeEach(() => {
   component = fixture.componentInstance;
  });

 it("should test GetData", () => {
  const spy = spyOn<any>(component, "GetData");
  // in order to spy on a private function the "<any>" flag is added

  component["GetData"](); // use this syntax to call a private function
  expect(spy).toHaveBeenCalled();
 });
});
Related