Tester
Tester

Reputation: 449

Error property does not exist in angular

I have a number type initialized at the beginning of my component class like this: My component class:

import { .....


@Component({
   ....
})
export class JhiLoginModalComponent implements  OnInit {
   
    a: number;
 

   
    ngOnInit() {
      this.method();

    }
    method() {
     a=3;
    }

My testing class:

import {...

  describe('LoginComponent', () => {
  
    let comp: ComponentClass;
        let fixture: ComponentFixture<ComponentClass>;
          beforeEach(async(() => {
            TestBed.configureTestingModule({
              ............
        }));
        
          beforeEach(() => {
            fixture = TestBed.createComponent(ComponnetClass);
            comp = fixture.componentInstance;
            ....
              });
              //MY TEST
                it ('Should print a value', async(() => {
fixture.detectChanges();
            console.log('lalalalla' + comp.method.a); //It prints lalalaundefined
            
        }));

It returns undefined when I print domElement and the error: Property a is undefined for type any

Do I make an error in injection?? How can I access the component elements otherwise?? If I use this number later it says that it is undefined.

Upvotes: 0

Views: 140

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18292

ngOnInit is not called when the component is created. It is the Angular engine which calls it, when the component is ready to be used (the inputs are set, including data-bound properties). Add a console.log to ngOnInit an you'll see it has not been called before the console.log in your test. You need to call fixture.detectChanges() first.

EDITED (based on your comment):

I just realised. You're logging comp.method.a, but comp.method is a function, so it does not have an a property. You should log comp.a:

console.log('lalala' + comp.a);

Upvotes: 1

Related Questions