I am using a private variable in Angular-6 service.ts.
private tagSubject = new Subject<any>();
It is been used like
sendNewTagMessage(message: string) {
this.tagSubject.next({ text: message });
}
clearNewTagMessage() {
this.tagSubject.next();
}
I want to write a unit test for tagSubject.
I cant do service.tagSubject.subscribe
in the spec.ts as it is giving error like Property 'tagSubject' is private and only accessible within class
. What can I do now. Please help.
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.
TestBed. createComponent() creates an instance of the BannerComponent , adds a corresponding element to the test-runner DOM, and returns a ComponentFixture .
Yes, this is expected. Keep in mind that private and other access modifiers are Typescript constructs, whereas Component/controller/template are angular constructs that Typescript knows nothing about.
And because it all compiles down to JavaScript, and the private fields are public JavaScript fields, we can use the named index to access the field. Similarly, this past week I was working on finishing up some Angular 2 code. And one of my tests was failing. Even though the code was working in Chrome fine.
Which means you can’t write your unit test in TypeScript and access the private variables. Or can you? One small little fact about TypeScript that we seem to forget is that it is just JavaScript with some sugar.
Angular component testing can be done manually by running the application yourself and checking to see if a component’s behavior is working as expected. But as web applications get larger and more complex, manually testing your components, consequently, becomes more time-consuming.
component['tagSubject']
or
(component as any).tagSubject
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With