如何在angular2中模拟@Input()对象?

Dan*_*Dan 8 karma-jasmine angular

我查看了angular2网站,并检查了很多SO帖子,我找不到用例说明的例子.

我想模拟来自具有@Input()标记的对象的数据.我的组件看起来像这样

...
export class DriftInfoDisplayComponent implements OnInit {

  showThisDriftInfo:boolean;
  headerText:string;
  informationText:string;
  linkText:string;
  @Input() inputInfo:DriftInfo;

  constructor(){}

  ngOnInit() {
    this.headerText = this.inputInfo.headerText;
    this.informationText = this.inputInfo.informationText;
    this.linkText = this.inputInfo.linkText;
    this.showThisDriftInfo = this.inputInfo.visible;
  }

  toggleDriftInfo(){
    this.showThisDriftInfo = ! this.showThisDriftInfo;
  }
}
Run Code Online (Sandbox Code Playgroud)

我的这个组件的单元测试文件是这样的

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


  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DriftInfoDisplayComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DriftInfoDisplayComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    const fixture = TestBed.createComponent(DriftInfoDisplayComponent);
    const drift = fixture.debugElement.componentInstance;
    expect(drift).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

我想编写一个测试,在DriftInfoDisplayComponent中调用inputInfo:DriftInfo及其对象及其属性,以便我可以测试这些数据是否在html模板中正确显示.我怎样才能做到这一点?

感谢您提供的任何帮助!

joh*_*667 14

只需将其添加为被测组件的属性:

beforeEach(() => {
  const fixture = TestBed.createComponent(DriftInfoDisplayComponent);
  const drift = fixture.debugElement.componentInstance;
  const driftInfo: DriftInfo = new DriftInfo();
  drift.inputInfo = driftInfo;
});

it('should have input info', () => {
  expect(drift.driftInfo instanceof DriftInfo).toBeTruthy();
)};
Run Code Online (Sandbox Code Playgroud)


Dom*_*Dom 6

存根对象,例如:

const InputInfo = {
      headerText: 'headerText',
      informationText: 'informationText',
      linkText: 'linkText',
      visible: 'visible' };
Run Code Online (Sandbox Code Playgroud)

在每个之前为它分配同步中的组件属性:

beforeEach(() => {
  fixture = TestBed.createComponent(DriftInfoDisplayComponent);
  element = fixture.debugElement.nativeElement;
  component = fixture.debugElement.componentInstance;
  component.inputInfo = InputInfo; // Assign stub to component property
  fixture.detectChanges(); // calls NgOnit  
});
Run Code Online (Sandbox Code Playgroud)

测试您的模板:

it('should have a header', () => {
 const header = element.querySelector('h1').textContent;

 expect(header).toBe('headerText');
});
Run Code Online (Sandbox Code Playgroud)