如何在角度组件的测试中模拟 @INPUT 值

use*_*388 3 input mocking testcase angular

在我的 angular 应用程序中,我正在为具有 @Input 值的组件编写测试用例。如何模拟 @Input 值。主组件的 testSave() 方法使用子组件的 InputObject 的 id。当我运行测试用例时,它说 undefined 是“this.subComponent.InputObject.id;”处的一个对象

export class SubComponent implements OnInit {
  @Input() inputObj: InputObject;
}

export class MainComponent implements OnInit {
  @Input() subComponent: SubComponent;

  testsave() {
  this.subComponent.InputObject.id;
  }
}

export class InputObject {
  contructor(id:string, name: string)
}
Run Code Online (Sandbox Code Playgroud)

测试用例:

 it('should save', fakeAsync(()  => {
//     const event: MockEvent = new MockEvent();
//     fixture = TestBed.createComponent(MainComponent);
//     component = fixture.componentInstance;
 });
Run Code Online (Sandbox Code Playgroud)

Buc*_*ski 5

由于subComponent并且inputObj是公开的,您可以简单地覆盖它,如果您进行测试,MainComponent您可以拥有以下内容:

component.subComponent = {inputObj: {id: 'someId', name :'someName'}};
Run Code Online (Sandbox Code Playgroud)