【问题标题】:Angular2 whenStable() not working with observable?Angular2 whenStable() 不能与 observable 一起使用?
【发布时间】:2017-06-06 07:32:40
【问题描述】:

我正在从一个 Angular2 组件的 ngOnInit 方法中运行一个 http 调用(使用 obervable):

ngOnInit() {
     this.descriptorService.generateDescriptors(new Server());
     this.fetchData();
}

fetchData () {
  console.log('Starting Http call');
  this.dataService.listAll(Server).subscribe(
     servers=>{console.log('Http Call done');this.listServers=servers},
     error=>console.log(error)
  );
}

使用以下 dataService.listAll():

listAll(zeClass:typeof Model): Observable<T[]> {
  console.log('Http call begin');
  return this.http.get(this.calculateUrl(zeClass))
    .map(this.extractData)
    .map((jsonArray)=>{
       let data:Array<ModelInterface>=new Array<ModelInterface>();
       if (isArray (jsonArray)) {
             console.log('Http call in');
         ...
       return data;
     })
    .catch(this.handleError);
 }

当我为此组件运行以下单元测试时(http 是用 InMemoryWebApiModule 模拟的):

it('should display the list of servers', async(() => {
  fixture.detectChanges();
  console.log('Before whenStable():'+fixture.isStable());
  fixture.whenStable().then(()=>{
    console.log('In whenStable()');
    fixture.detectChanges();
    let de:Array<DebugElement> = fixture.debugElement.queryAll(By.css('md-list-item'));

    expect(de.length).toBeGreaterThan(1);
  });
console.log('After whenStable():'+fixture.isStable());
}));

然后我在控制台中得到以下日志:

 LOG: 'Starting Http call'
 LOG: 'Http call begin'
 LOG: 'Before whenStable():false'
 LOG: 'After whenStable():false'

你可以看到whenStable()里面的测试代码根本没有运行... 为什么?

【问题讨论】:

  • 为什么你认为这不起作用?这是一个异步回调,这就是应该发生的。您是否尝试过使用done
  • whenstable() 中的第一行是我从未在控制台中看到的日志。我看到一些关于“完成”的帖子,但我不确定它是什么
  • 是的,因为它是异步的,所以在回调被回调之前测试就结束了……返回。 “After whenStable” 是指回调运行之后。
  • 是的,但是 whenstable() 不应该等到所有 async() 操作都完成了吗?
  • 在所有操作完成之前,它不会调用回调。请按照我上面的建议查看 Jasmine 的done

标签: unit-testing angular testing observable


【解决方案1】:

感谢@jonrsharpe 为我指明了正确的方向。 实际上,我不得不使用 Jasmine done 和 spies。

有关信息,这里是工作测试代码:

 beforeEach(inject([GenericDataService], (dataService) => {
   spy = spyOn(dataService,'listAll').and.callThrough();
   ...
 }

it('should display the list of servers', done => {
  fixture.detectChanges();

  spy.calls.mostRecent().returnValue.subscribe (() => {
    console.log('In spy()');
    fixture.detectChanges();
    let de:Array<DebugElement> = fixture.debugElement.queryAll(By.css('md-list-item'));

    expect(de.length).toBeGreaterThan(1);
    done();
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 2016-11-15
    • 2017-03-22
    • 2017-02-10
    • 2021-10-21
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多