簡體   English   中英

未調用 Angular 單元測試中的事件發射器

[英]Event emitter in Angular unit test isn't called

鑒於此組件...

export class MyComponent {
  @Output() onActivateEditMode = new EventEmitter<boolean>();

  constructor() {}

  emitActivateEditMode(flag: boolean) {
    this.onActivateEditMode.emit(flag);
  }

...而這個模板...

<a (click)="emitActivateEditMode(true)" data-test-start-edit-project-btn>Edit</a>

...然后此測試失敗:

describe('MyComponent', () => {

  ... (TestBed imports etc)

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    spyOn(component, 'emitActivateEditMode');
    fixture.detectChanges();
  });

  it('should activate editmode on click', () => {
    const onActivateEditModeSpy = jest.spyOn(
      component.onActivateEditMode,
      'emit'
    );
    const startEditProjectBtn = fixture.debugElement.nativeElement.querySelector(
      '[data-test-start-edit-project-btn]'
    );
    startEditProjectBtn.dispatchEvent(new Event('click')); // startEditProjectBtn.click() doesn't change the result, too
    fixture.detectChanges();
    expect(component.onActivateEditMode.emit).toHaveBeenCalledWith(true);
    // expect(onActivateEditModeSpy).toHaveBeenCalledWith(true) ... doesn't change the result, too
  });

});

測試 output 為:

Expected: true
Number of calls: 0

該功能在瀏覽器中有效,但此測試設置中的某些內容是錯誤的。

我假設您同時使用 Jasmine 和 Jest。 問題是,當您監視 function ( spyOn ) 時,您實際上只是在監視 function 的調用和實現細節 Z34D1F91FB2E514B9576FAB1A75A 要獲得完整的實現細節,您可以執行spyOn(component, 'emitActivateEditMode').and.callThrough(); 但我認為對你來說,它是不需要的。

describe('MyComponent', () => {

  ... (TestBed imports etc)

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    // remove the mock/spyOn to the function emitActivateEditMode
    fixture.detectChanges();
  });

  it('should activate editmode on click', () => {
    // spy on emit calls on onActivatedEditMode
    const emitSpy = spyOn(component.onActivateEditMode, 'emit');
    const startEditProjectBtn = fixture.debugElement.nativeElement.querySelector(
      '[data-test-start-edit-project-btn]'
    );
    startEditProjectBtn.click();
    fixture.detectChanges(); // fixture.detectChanges is not needed here, only if you want to see the update in the HTML.
    expect(emitSpy).toHaveBeenCalledWith(true);
});

暫無
暫無

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

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