簡體   English   中英

Angular 單元 - 測試如何訂閱事件發射器

[英]Angular Unit - Testing how to subscribe event emitter

在我的單元測試中,我想用ngOnDestroyed方法中的這三個 eventemitter 調用openDialogopenPdfgetPath 我怎么給他們打電話?

component.ts

pdfPath: string = ''; // will be edited later

@Output() openDialog = new EventEmitter();
@Output() openPdf = new EventEmitter();
@Output() getPath: EventEmitter<string> = new EventEmitter();
 
getData() {
  // ...
  this.openDialog.emit(true);
}

showData() {
  // ...
  this.openPdf.emit();
}

fetchData() {
  // ...
  this.getPath.emit(this.pdfPath);
}


ngOnDestroyed(): void {
    this.openDialog.unsubscribe();
    this.openPdf.unsubscribe();
    this.getPath.unsubscribe();
}

我試過在beforeEach中這樣調用它們並使用 spyOn(component.openDialog, 'subscribe'); ,但這不起作用:

const emitter = new EventEmitter();
component.openErrorMessageDialog = emitter;
component.loadedPdf = emitter;
component.getPdfLocalPath = emitter;
emitter.emit(true);

我希望我已經正確理解了你的問題。

如果你想檢查emit function 是否被調用,那么你可以用間諜來檢查:

it('#getData should emit openDialog', () => {
  const emitSpy = spyOn(component.openDialog, 'emit');

  component.getData();

  expect(emitSpy).toHaveBeenCalled(); // checks if `openDialog.emit()` has been called
  expect(emitSpy).toHaveBeenCalledWith(true); // checks if `openDialog.emit()` has been called with `true`
});

有關間諜的更多信息,只需搜索“ Jasmine 間諜”即可。

如果你只是在單元測試中使用emit() function 那么你可以使用自動生成的component變量來做到這一點:

describe('BookShelfComponent', () => {
  let component: BookShelfComponent; // your component
  let fixture: ComponentFixture<BookShelfComponent>;

  // ...

  beforeEach(() => {
    fixture = TestBed.createComponent(BookShelfComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('#openDialog.emit should emit openDialog', () => {
    const emitSpy = spyOn(component.openDialog, 'emit');

    component.openDialog.emit(); // call `emit()`

    expect(emitSpy).toHaveBeenCalled(); // only for the demonstration that `emit()` was executed
  });
});

如果那沒有回答您的問題,請再次嘗試更清楚地描述您的問題。

您的代碼中的另一個異常是您的ngOnDestroy() 您將unsubscribe()調用到您的EventEmitter ,這是您不應該做的。 因為 EventEmitter 應該只用於從組件發出事件,因此不應該訂閱它們,所以不需要取消訂閱。
如果您需要訂閱它,您應該使用Subject而不是帶有 @Output 的@Output

暫無
暫無

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

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