0

For some reason these two specs are passing, however the second spec is testing interpolation within the template, with async data from a service. Why is it not necessary to wrap the callback function with async?

describe('SaangComponent', () => {
  let component: SaangComponent;
  let fixture: ComponentFixture<SaangComponent>;
  let compiled: HTMLElement;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SaangComponent ],
      providers: [
        {provide: GetSomeService, useValue: getSomeServiceMock}
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SaangComponent);
    component = fixture.componentInstance;
    compiled = fixture.debugElement.query(By.css('h1')).nativeElement;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should update the h1 attribute with the title', () => {

    fixture.detectChanges();
    const expectedText = compiled.innerHTML;
    expect(expectedText).toEqual('lord');
  });
});

const getSomeServiceMock = {
  getSomeData() {
    return Observable.of({title: 'lord'});
  }
};
S.Baah
  • 11
  • 3

2 Answers2

0

It is necessary to wrap callback function in testing block with async or fakeAsync Angular helpers if a function is expected to be asynchronous.

getSomeServiceMock uses Observable.of and is synchronous. This is why async is optional.

If the components involved in this test suit doesn't contain asynchronously loaded components, async in beforeEach is optional, too.

As a rule of thumb, all testing blocks may be wrapped with fakeAsync. It's faster than async and will let you know if it's unsuitable (when real asynchronous operations happen in a block).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
0

I assume that 'getSomeData' is called in the component's ngOnInit lifecycle hook. If so the mock response you are using is already used when you are creating the component.

Kozlo
  • 1