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

Viewed 347

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?

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

You test private methods by calling public methods. Create a test bed for your component, create a mock of myServiceFacade such that it dispatches a reload event and verify that after that myString is equal to 'test'

Related