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()
你应该试试这个:
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);
}));
使用回调函数可以更轻松地做到这一点:
// 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会抱怨。测试将成功,但会引发警告。
好的,
我在测试中使用以下反应式形式和伪造器来工作。您不必使用Faker。
<div [formGroup]="todoItemFormGroup">
<input type="checkbox" (click)="checkedInput()" formControlName="isComplete" />
....
</div>
我正在使用反应式表单组
todoItemFormGroup = new FormGroup(
{
name: new FormControl('', [Validators.required]),
isComplete: new FormControl(false)
}
)
checkedInput() {
this.updateItemtoParent.emit({
...this.todoItem.getValue(), //this is my BehaviorSubject<TodoItemDto>
...this.todoItemFormGroup.getRawValue() as TodoItemDto, //this is from the formgroup
} as TodoItemDto);
}
最后我的规格看起来像这样:
it("Should emit the checklist item when the checkbox is checked", () => {
spyOn(component.updateItemtoParent, 'emit');
const fakeTodoItem: TodoItemDto = {
id: faker.datatype.uuid(),
name: faker.name.firstName(),
checklistId: faker.datatype.uuid(),
isComplete: false
};
component.todoItem.next(fakeTodoItem);
fixture.detectChanges();
const compiled = fixture.debugElement.query(By.css('input[type=checkbox]'));
compiled.nativeElement.click();
fixture.detectChanges();
expect((component.todoItemFormGroup.getRawValue() as TodoItemDto).isComplete).toEqual(true);
expect(component.updateItemtoParent.emit).toHaveBeenCalledWith(fakeTodoItem);
});