Angular 无法读取属性';名称';在规范中未定义的

Angular 无法读取属性';名称';在规范中未定义的,angular,testing,jasmine,Angular,Testing,Jasmine,我正在从事Angular8项目,使用jest和jasmine作为测试配置 .ts // all imports are done correctly @Component({ selector: 'app-xyz', templateUrl: './xyz.component.html', styleUrls: ['./xyz.component.scss'] }) export class XYZComponent implements OnInit { public in

我正在从事Angular8项目,使用jest和jasmine作为测试配置

.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();
  });

});
即使你正在做:

component.info = {
  'list':
  [
    {
      'fName':'Eddy',
      'lName':'He',
      'number: 123
    }
  ]
};
在调用
component.ngOnInit()
之前,这是不够的,因为在
ngOnInit()
方法中,您正在执行
this.info=this.infoService.getData(),覆盖您的
信息
属性

我相信在这个规范上下文中,这个方法返回
undefined

更好的方法是模拟服务,提供一个假
getData
方法,返回您希望组件处理的数据


或者您可以将
this.info=this.infoService.getData()
移动到构造函数中,因为它不依赖于输入数据,这将使重写正常工作。

您可以添加
this.infoService.getData()的内容吗?我认为问题可能存在。是的,我可以,但是我应该在.spec文件中添加到哪里?你能指导我吗?哦,我指的是方法的内容,作为一个单独的代码片段。等等,nvm,我发现了错误,正在写回复。好的,我将尝试第一种方法来模拟服务,并为其提供一个假呼叫。。。你能帮我举一些关于如何模拟服务的例子吗?参见,搜索“MockUserService”。
component.info = {
  'list':
  [
    {
      'fName':'Eddy',
      'lName':'He',
      'number: 123
    }
  ]
};