我想测试使用异步管道的组件。这是我的代码:

@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');

});

但是测试失败了。似乎Angular由于某种原因没有执行到Observable。我缺少什么?

当我尝试使用do运算符记录可观察值时,在浏览器控制台中看不到任何输出。

最佳答案

据我所知,您不能将fakeAsync与异步管道一起使用。我很想被证明是错误的,但是我尝试了一段时间,却无济于事。相反,请使用async实用程序(为了避免与realAsync关键字混淆,我将其别名为async)和await用作Promise包装的setTimeout而不是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');
  }));
});

10-02 18:12