测试用例,在复选框更改时发出事件

时间:2019-03-29 16:16:06

标签: angular karma-jasmine

HTML:

<checkbox (change)="onChange()" [(ngModel)]="ngModel"> Checkbox </checkbox>

ts:

ngModel: boolean;

@Output() checkboxEvent = new EventEmitter<any>();

onChange() {
this.checkboxEvent.emit(this.ngModel);
}

测试案例:

it('TC 3: should emit an event on change of checkbox', async(() => {
    spyOn(component.checkboxEvent, 'emit');
    component.onChange();
    const edlCheckbox = fixture.debugElement.query(By.css('checkbox ')).nativeElement;
    edlCheckbox.dispatchEvent(new Event('change'));
    fixture.detectChanges();
    expect(component.checkboxEvent ).toHaveBeenCalled();
    expect(component.checkboxEvent .emit).toHaveBeenCalledWith(true);
  }));

错误:

Failed: <toHaveBeenCalled> : Expected a spy, but got EventEmitter(
{ _isScalar: false, observers: [  ], closed: false, 
isStopped: false, hasError: false, thrownError: null,
 __isAsync: false, emit: spy on emit }).
Usage: expect(<spyObj>).toHaveBeenCalled()

2 个答案:

答案 0 :(得分:0)

您应该尝试以下操作:

it('TC 3: should emit an event on change of checkbox', async(() => {
    spyOn(component.checkboxEvent, 'emit');
    spyOn(component, 'onChange');
    const edlCheckbox = fixture.debugElement.query(By.css('checkbox ')).nativeElement;
    edlCheckbox.click();
    fixture.detectChanges();

    expect(component.onChange).toHaveBeenCalled(); 
    expect(component.checkboxEvent.emit).toHaveBeenCalledWith(true);

  }));

答案 1 :(得分:0)

您可以使用回调函数轻松完成此操作:

                                                     // vvvv
it('TC 3: should emit an event on change of checkbox', (done) => {
                                         // vvvv
    component.checkboxEvent.subscribe(() => done());
    fixture.debugElement.query(By.css('checkbox ')).nativeElement.click()
}

通过使用done函数,如果未在5秒内(可自定义)调用done函数,则测试将失败。

注意:此测试不需要任何expect(),但如果您进行不带expect()通话的测试,则Karma会抱怨。测试将成功,但会引发警告。