mardi 4 février 2020

Cannot read property 'name' of undefined in a spec

I am working on Angular8 project using jest and jasmine as the testing configurations.

.ts

// all imports are done correctly

@Component({
  selector: 'app-xyz',
  templateUrl: './xyz.component.html',
  styleUrls: ['./xyz.component.scss']
})
export class XYZComponent implements OnInit {

  public info;
  public number;

  constructor(private InfoService: infoService ) {
  }

  ngOnInit() {
    this.getInfo();
  }

  public getInfo() {    
   this.info =  this.infoService.getData();   
   this.number = this.info.list[0].number;
  }

}

.spec

// all imports are done 

describe('XYZComponent', () => {
  let component: XYZComponent;
  let fixture: ComponentFixture<XYZComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ //imports done ],
      declarations: [ XYZComponent],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(XYZComponent);
    component = fixture.componentInstance;

    component.info = {
      'list':
      [
        {
       'fName':'Eddy',
       'lName':'He',
       'number: 123
     }
    ]
  }; 
   component.ngOnInIt(); 
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

When In the .spec files ngOnInit() is called it throws errors as follows :

● XYZComponent › should create

TypeError: Cannot read property 'list' of undefined

  43 |    this.info =  this.infoService.getData();
> 44 |    this.number = this.info.list[0].number;
     |                               ^
  46 |   }

Aucun commentaire:

Enregistrer un commentaire