I've been doing some experiments with tests in Angular and accessing private methods.
In JavaScript, private methods do not exist, so even if something is marked as private in a TypeScript class; at the end of the day it is still accessible on an object instance if you try to do so at runtime.
Consider this:
2 private privateMethod(input: string): string {
3 return input;
4 }
5}
Now, create an instance:
And access the private method:
For the purposes of this, sample, I'm just sending in some value to the method and using console.log() to dump the output to the console.
Instead of Object.property notation, I'm using object array notation to drill into the method.
TSLint is giving me an error
The error says:
This code will run in a browser without issues.
I could go change the linting rules universally in the app, or I could tell the app to ignore this one line. For the purposes of this post, I want to do the latter.
You can tell TSLint to ignore that line by using the tslint:disable-next-line directive:
2console.log(foo['privateMethod']('something'));
See that IntelliJ no longer shows any errors:
Primarily, this is only something I'd use within tests when I want to access a private method directly. We could argue about whether that is a good idea or not all day but I often decide to do so when writing unit tests.