簡體   English   中英

如何使用可觀察的輸入測試角度組件

[英]How to test Angular component with Observable Input

我正在嘗試測試基本上接收到一個Observable的Angular Component ,並根據該Observable發出的值更改其template 這是一個簡化的版本:

@Component({
    selector: 'async-text',
    template: `
        <span>{{ text | async }}</span>
    `,
})
export class AsyncTextComponent {    
    @Input() text: Observable<string>;
}

我想測試一下,目前這是我使用rxjs-marbles (雖然不是必須的)。

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AsyncTextComponent } from './async-text.component';

describe('AsyncTextComponent', () => {
  let component: BannerComponent;
  let fixture: AsyncTextComponent<AsyncTextComponent>;

  it('...',
    marbles(m => {
      fixture = TestBed.createComponent(AsyncTextComponent);
      component = fixture.componentInstance;
      component.text = m.cold('-a-b-c|', {
        a: 'first',
        b: 'second',
        c: 'third',
      });

      fixture.detectChanges();
      expect(component.nativeElement.innerHTML).toContain('first');

      fixture.detectChanges();
      expect(component.nativeElement.innerHTML).toContain('second');

      fixture.detectChanges();
      expect(component.nativeElement.innerHTML).toContain('third');
    })
  );
});

顯然,這是行不通的。 我的問題是,我沒有找到一種方法可以在每個expect之間以給定數量的“框架”推進TestScheduler。

如何手動跳過幀? 或者,是否有更好的方法來測試上述組件/場景(收到Observable Angular組件,鑒於Observable的發射,我想測試其行為)。

我確實看到了.flush() ,但是正如所記錄的那樣,它運行所有Observable的發射,因此我將到達最終狀態,並且無法測試狀態之間的不同轉換。

謝謝

您不必使用任何庫對其進行測試。 甚至,您可以在Angular的上下文之外進行測試。

無論如何,這是解釋。

為了測試這一點,我建議使用變量。 但是,如果您想堅持自己的方法,就應該堅持下去。

it('should display first', done => {
  // Mock your component
  component.text = Observable.of('first');
  // Detect template changes
  fixture.detectChanges();
  // trigger a change detection, just in case (try without, you never know)
  setTimeout(() => {
    // Get the element that is displaying (tip: it's not your whole component)
    const el = fixture.nativeElement.querySelector('span');
    // Test the innet text, not the HTML
    // Test with includes, in case you have spaces (but feel free to test without includes)
    expect(el.innerText.includes('first')).toEqual(true);
    // End your test
    done();
  });
});

暫無
暫無

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

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