0

鉴于此组件...

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
  });

});

测试输出为:

Expected: true
Number of calls: 0

该功能在浏览器中有效,但此测试设置中的某些内容是错误的。

4

1 回答 1

1

我假设您同时使用 Jasmine 和 Jest。问题在于,当您监视函数 ( spyOn) 时,您实际上只是在监视函数以进行调用,而实现细节就消失了。要完整地了解实施细节,您可以这样做,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);
});
于 2020-06-29T18:38:40.737 回答