Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a private variable in spec.ts, Angular6

Tags:

angular

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.

like image 541
raju Avatar asked Mar 25 '19 11:03

raju


People also ask

Can we write test cases for private methods Angular?

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.

What does TestBed createComponent do?

TestBed. createComponent() creates an instance of the BannerComponent , adds a corresponding element to the test-runner DOM, and returns a ComponentFixture .

Is it possible to use private modifier in angular components?

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.

Why do we use named indexes for private fields in angular?

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.

Can you use private variables in typescript unit tests?

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.

How to test angular components manually?

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.


1 Answers

component['tagSubject']

or

(component as any).tagSubject

like image 79
elzoy Avatar answered Sep 20 '22 06:09

elzoy