簡體   English   中英

Jasmine 使用 ngIf 異步可觀察的大理石測試 pipe

[英]Jasmine marble testing observable with ngIf async pipe

我想用 jasmine-marble 測試來測試Observable ,但不幸的是我不知道如何觸發ngIf的更改檢測,這應該呈現組件。

這是我的 class 的簡化版本:

export class MyComponent implements OnInit {
  data$: Observable<{data: any[]}>;

  constructor(private baseService: BaseService) { }

  ngOnInit(): void {
    this.data$ = this.baseService.get(endpoint);
  }
}

還有我的 html 文件:

<custom-component *ngIf="data$ | async as value" [data]="value.data">
    ...
</custom-component>

這是我當前的測試,失敗了:

it ('should display custom component', fakeAsync(() => {
    const expected = cold('a|',  {a: {data: [{id: 1}]}});
    baseServiceStub.get.and.returnValue(expected);
    component.ngOnInit();
    fixture.detectChanges();
    tick();
    expect(component.data$).toBeObservable(expected); // this passes and the observable also holds the correct value
    expect(baseService.get).toHaveBeenCalledWith(endpoint); // this passes aswell
    component.data$.subscribe(val => {
      console.log(val); // here I can log the correct value of the observable ( {data: [{id:1}]})
    });
    expect(fixture.debugElement.query(By.css('custom-component'))).not.toBeNull(); // this fails
}));

不幸的是我得到的都是這個

Error: Expected null not to be null.

服務或可觀察對象本身沒有問題,但在我看來,由於某種原因,DOM 不會觸發使用異步 pipe 渲染組件的更改檢測。

PS:當我使用getTestScheduler().flush()時,我收到錯誤Can't subscribe to undefined代替。

您的訂閱是異步的。 這意味着您的console.log可以在您最后一次expect之后觸發。 在您最后的期望中,數據可能尚未加載,因此該值未定義。

使用tick(100)而不是tick()可能會起作用。 請注意,這將使您的測試慢 100 毫秒。

你也可以切換到 async 並等待 observable 返回一個值:

it ('should display custom component', async(() => {
    ...
    // tick(); //dont call this
    ...
    await component.data$.pipe(take(1)).toPromise()
    expect(fixture.debugElement.query(By.css('custom-component'))).not.toBeNull(); 
}));

我通過創建另一個測試套件解決了這個問題,我在其中手動定義了 observable 的值。 我對這種方法並不完全滿意,但它是我的問題的解決方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM