karama fake async tick没有按预期工作



下面是测试中相关的部分。如果我添加setTimeout,这个测试可以100%工作,但理想情况下不想这样做。我想让测试在检查模板之前等待一定的时间,现在发生的是它的检查太快了,模板中的ngIf检查失败了,所以检查失败了。已经尝试了相当多的事情和手动调用完成的组合,并使用fixture.whenStable()似乎不能得到任何工作除了setTimeout

我想我期待tick()快进1.5秒而不实际拖延javascript,而一些异步任务在这种情况下,它的第二个可观察对象在组合最新


mockCycleService = jasmine.createSpyObj('CycleService', ['getPageDuration', 'nextPage'])
mockCycleService.getPageDuration.and.returnValue(800);
mockCycleService.nextPage.and.returnValue(of());
fit('should display a blog post', fakeAsync(() => {
// setTimeout(()=>{

tick(1500); //larger than set timeout have tried so many higher numbers 
fixture.detectChanges();
const cards = fixture.debugElement.queryAll(By.css('.csCard'));
console.log(cards)
expect(cards).not.toBeNull();
expect(cards.length).toEqual(1);
// },70)
}));

这是一个组件,它获取一个博客列表然后将它与一个计时器结合来旋转博客文章的内容

this.timerSubscription$ = timer(1,this.cycleService.getPageDuration());
this.blogs$ = combineLatest([this.blogPosts$, this.timerSubscription$]).pipe(
tap(console.log), //this fires in console log after cards in test
map(r => r[0].map(a => a)),
tap(() => this.curInd = this.curInd + 1),
takeWhile((response) => this.curInd < response.length),
finalize(() => this.cycleService.nextPage())
);

模板处理订阅…

<div *ngIf="blogs$ | async as blogs">
<div class="csCard" *ngFor="let blog of blogs>
....

有时你需要在使用fakeAsync时尝试一些组合,例如

tick()
fixture.detectChanges();
flush();
fixture.detectChanges();

如果你调用fixture.detectChanges();不止一次,它只适用于Default变化检测策略,而不是OnPush-但这可以在TestBed中覆盖,如果需要

最新更新