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

问题描述 投票:0回答:2

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()
angular karma-jasmine
2个回答
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);

  }));

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函数,如果在5s内没有调用done函数(可自定义),测试将失败。

注意:这个测试不需要任何expect()但是如果你在没有expect()电话的情况下进行测试,Karma会抱怨。测试将成功,但会引发警告。

© www.soinside.com 2019 - 2024. All rights reserved.