在编写单元测试时,确保在每个异步管道的前面设置fakeAsync()
,随后使用tick()
方法模拟异步操作完成,以便正确触发管道更新。以下是示例代码:
it('should update async pipe correctly', fakeAsync(() => {
const testValue = 'test';
// Mock async data source
spyOn(myService, 'getData').and.returnValue(of(testValue).pipe(delay(100)));
// Trigger component initialization
fixture.detectChanges();
// Make sure async pipe is updated correctly
expect(fixture.debugElement.query(By.css('div')).nativeElement.textContent).toBe('');
tick(100);
expect(fixture.debugElement.query(By.css('div')).nativeElement.textContent).toBe(testValue);
}));