Angular testing async pipe does not trigger the observable
Asked Answered
I

3

28

I want to test a component that uses the async pipe. This is my code:

@Component({
  selector: 'test',
  template: `
    <div>{{ number | async }}</div>
  `
})
class AsyncComponent {
  number = Observable.interval(1000).take(3)
}

fdescribe('Async Compnent', () => {
  let component : AsyncComponent;
  let fixture : ComponentFixture<AsyncComponent>;

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

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


  it('should emit values', fakeAsync(() => {

    tick(1000);
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('div')).nativeElement.innerHTML).toBe('0');

});

But the test failed. It's seems Angular does not execute to Observable from some reason. What I am missing?

When I'm trying to log the observable with the do operator, I don't see any output in the browser console.

Illconsidered answered 29/6, 2017 at 9:36 Comment(0)
Z
10

As far as I can tell, you can't use fakeAsync with the async pipe. I would love to be proven wrong, but I experimented for a while and couldn't get anything to work. Instead, use the async utility (which I alias as realAsync to avoid confusion with the async keyword) and await a Promise-wrapped setTimeout instead of using tick.

import { async as realAsync, ComponentFixture, TestBed } from '@angular/core/testing';

import { AsyncComponent } from './async.component';

function setTimeoutPromise(milliseconds: number): Promise<void> {
  return new Promise((resolve) => { 
    setTimeout(resolve, milliseconds);
  });
}

describe('AsyncComponent', () => {
  let component: AsyncComponent;
  let fixture: ComponentFixture<AsyncComponent>;
  let element: HTMLElement;

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

  beforeEach(() => {
    fixture = TestBed.createComponent(AsyncComponent);
    component = fixture.componentInstance;
    element = fixture.nativeElement;
    fixture.detectChanges();
  });

  it('should emit values', realAsync(async () => {
    await setTimeoutPromise(1000);
    fixture.detectChanges();
    expect(element.getElementsByTagName('div')[0].innerHTML).toEqual('0');
  }));
});
Zampardi answered 3/12, 2019 at 19:30 Comment(5)
thanks, that actually did it for me! But the fixture.detectChanges(); is also instrumental. I had one already at the end of the beforeChanges, like you, but that wasn't enoughRuthenic
You can definitely use fakeAsync tests for components that use the async pipe. Maybe the problems you've had are related to some need to flush the microtask queue at the right times? I use a helper I've created for my component tests that usually takes care of all those kinds of details for me: ComponentContextNext.Inaccuracy
Thanks man, this approach works perfectly!Niobous
tried using fakeAsync, done, setTimeout in test but nothing worked. This worked fine for me. ThanksAisne
Warning: Although this solution works but this is not efficient, I can't type everything here in the comment so see my answer belowAppropriation
B
2

I had this problem, I'm surprised nobody looked up any real solution.

Possible solutions

  • Your template might not be rendered in your test, especially if you are overriding it. So, the | async operation won't trigger.
  • You aren't using fixture.detectChanges() enough to allow template rendering. Rendering occurs after OnInit stage. So make sure you use fixture.detectChanges at least 2 times.
  • Maybe you have setTimeout operations pending, for example debounce(100) would require a tick(100) to resolve (within a fakeAsync test).

Cheers

Bondon answered 26/11, 2020 at 23:25 Comment(0)
A
0

The solution is very simple as pointed by delpo already, you have to call fixture.detectChanges() before tick() because without initial render template will not load, hence async pipe is not triggered.

it('should emit values', fakeAsync(() => {
    const fixture = TestBed.createComponent(AppComponent);

    fixture.detectChanges(); // call this initially as well before tick

    tick(1000);
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('div')).nativeElement.innerHTML).toBe('0');

    discardPeriodicTasks();
}));

Also don't use setTimeout because this will actually delay your test with 1 second, I know 1 second may not matter for few people but imagine you have n no of test, that will delay the test every 1 second or whatever the time you have provided.

For these type of tests angular introduced fakeAsync which wraps all the async operations including setTimeout and setInterval and when tick is called it fast-forward the time without needing to actually wait.

Appropriation answered 18/7 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.