How to mock an @Input() object in angular2?

Dan picture Dan · May 30, 2017 · Viewed 16.6k times · Source

I have looked on the angular2 website, as well as checked many SO posts and I could not find an example that illustrates by use case.

I want to mock data from an object that has an @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 DriftInfoDisplayComponent and its properties so that I can test that this data is being displayed properly in the html template. How can I do this?

Thanks for any help that may be provided!

Answer

joh04667 picture joh04667 · May 30, 2017

Just add it as a property of the component-under-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();
)};