0

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.

3
  • Why do you have an async beforeEach and a regular one? what is inside of them? you misspelled ComponnetClass, but I assume in your actual code it's correct? Commented May 4, 2018 at 12:18
  • Yeah because my code is too long, so I am simplifying it for you. Inside beforeEach and async are the imports and the inicialization of teh testing environment that makes angular by default :) Commented May 4, 2018 at 12:21
  • Does the property .method.a exist on ComponentClass? If a is a variable inside a function, it exists only as long as the function is being processed. Commented May 4, 2018 at 12:28

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah Im sorry I didnt put it there. I have a fixture.DetectChanges inside the test method
Edited. I think I realised what the problem is
It doesnt give teh error that the property is undefined, but prints lalalundefined. I want to print lalalala3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.