admin管理员组

文章数量:1183211

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

  beforeEach(() => {
    fixture = TestBed.createComponent(AsyncComponent);
    component = fixtureponentInstance;
    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.

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.

Share Improve this question asked Jun 29, 2017 at 9:36 ng2userng2user 2,0776 gold badges25 silver badges31 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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');
  }));
});

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

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.

You have to include AsyncPipe in the imports of your component as well as in the declarations of the TestBed:

import { AsyncPipe } from '@angular/common';
@Component({
  selector: 'test',
  imports: [ AsyncPipe ]
  template: `
    <div>{{ number | async }}</div>
  `
})
class AsyncComponent {
  number = Observable.interval(1000).take(3)
}
TestBed.configureTestingModule({
  declarations: [ AsyncComponent, AsyncPipe ]
}).compileComponents();

本文标签: javascriptAngular testing async pipe does not trigger the observableStack Overflow