How to trick @Input () object in angular2?

I have looked at the angular2 website and also checked many SO posts and I could not find an example to illustrate using use case.

I want to mock data from an object with @Input () tag. My component looks like this

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

      

My unit test file for this component looks like this

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

      

I would like to write a test that mocks the inputInfo: DriftInfo and its object in the DriftInfoDisplayComponent and its properties so that I can check that this data is displayed correctly in the html template. How can i do this?

Thanks for any help that can be provided!

+3


source to share


2 answers


Just add it as a property of the component-sub-test:



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

      

+6


source


Lock the object, for example:

const InputInfo = {
      headerText: 'headerText',
      informationText: 'informationText',
      linkText: 'linkText',
      visible: 'visible' };

      

Assign component property in synchronous before each:



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

      

Check your template:

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

 expect(header).toBe('headerText');
});

      

+1


source







All Articles