Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test a private method in angular/typescript?

I have an Angular 11 project and I don't know how to Test a private method.

here is an Code Example:

ngOnInit() {
    this.addSubscription(this.myServiceFacade.myService.reloadEvent.subscribe(
        this.foo.bind(this)
    ));
}

private foo() {
    this.myString = 'test';
    this.bar(MyStatus.Enum);
}

Any ideas?

like image 607
Matthias Avatar asked Sep 06 '25 21:09

Matthias


1 Answers

DISCLAIMER This trick should only be used for tests, never for production!

There's a typescript trick you can use to access private members - use the indexing operator with the member in a string, thus:

someObjectWithPrivateMembers['privateMemberName']();

And the nice thing is, you get to keep type safety, because typescript looks up the type of the private member.

Be careful not to have a typo in the string (to a non existent member), because typescript won't complain, and the result will be undefined with a type of any.

like image 129
Aviad P. Avatar answered Sep 10 '25 14:09

Aviad P.