1

I am just trying to make this work.

it('should have expected <h1> text', async(() => {
  let fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();

  const sectionEl = fixture.debugElement.query(By.css("section"));

  spyOn(fixture.debugElement.componentInstance, "runMe");

  sectionEl.nativeElement.click();
  expect(fixture.debugElement.componentInstance.runMe).toHaveBeenCalled();

  expect(sectionEl.nativeElement.textContent).toBe("changed!");

So, the runMe function did not change the section's text, but the spy shows runMe was called.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
coder
  • 353
  • 5
  • 18

1 Answers1

1

Hard to tell without seeing a more complete example. But with clicking stuff, it usually involves asynchronous event handling. Therefore we need to wait for the event handling to complete. In a test, how we can do that is by calling fixture.whenStable, which returns a promise. We can continue the test when the promise resolves.

sectionEl.nativeElement.click();
fixture.whenStable().then(() => {
  expect(fixture.debugElement.componentInstance.runMe).toHaveBeenCalled();

  fixture.detectChanges();
  expect(sectionEl.nativeElement.textContent).toBe("changed!");
});
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • I tried this earlier in my own project, and it doesn't work. I also tried something like this in my cloned local copy of the angular 2 quickstart github repo and it does not work. – coder Oct 07 '16 at 16:20
  • You should probably post a complete example for further help – Paul Samsotha Oct 07 '16 at 16:21
  • peeskillet, I am trying to set up a Plunkr for this. Can you help me make TestBed work in src/test.spec.ts. – coder Oct 12 '16 at 19:30
  • Here is the Plunkr - https://plnkr.co/edit/K0IyBnR8F4F7zOp6LETi?p=preview – coder Oct 12 '16 at 19:30