如何在 jasmine angular 中测试事件 html
How test event html in jasmine angular
我的项目中有一些功能,但我决定选择这个作为示例。我要测试的功能是这个
<mat-select
*ngIf="name != '' && formControl == undefined"
[placeholder]="placeholder"
[formControlName]="name"
[multiple]="multiple"
(selectionChange)="selectionChange($event)"
>
selectionChange = (event) => {
let emit: any[] = [];
if (this.multiple) {
emit = this.selectOptions.filter((item) => {
return event.value.find((item2) => item2 === item.value);
});
} else {
emit = [this.selectOptions.find((item) => item.value === event.value)];
}
this.onSelectionChange.emit(emit.map((item) => item.original));
};
而jasmine中使用spies的函数是这样的,我想调用selectionChange函数传递事件作为参数,但是没有成功
it('deverá chamar a função selectionChange', () => {
let select = fixture.debugElement.query(By.css('.mat-select')).nativeElement;
fixture.detectChanges();
spyOn(component,'selectionChange').and.callThrough();
component.selectionChange(select.event);
expect(component.selectionChange).toHaveBeenCalled();
});
我认为你可以在 DebugElement
上利用 triggerEventHandler
。
试试这个:
import { By } from '@angular/platform-browser';
...
it('deverá chamar a função selectionChange', () => {
let select = fixture.debugElement.query(By.css('mat-select'));
const selectSpy = spyOn(component, 'selectionChange').and.callThrough();
// the first argument is the event you want to trigger,
// the 2nd argument is the object that is emitted ($event)
// mock $event however you wish
select.triggerEventHandler('selectionChange', { value: [] });
expect(selectSpy).toHaveBeenCalled();
});
我的项目中有一些功能,但我决定选择这个作为示例。我要测试的功能是这个
<mat-select
*ngIf="name != '' && formControl == undefined"
[placeholder]="placeholder"
[formControlName]="name"
[multiple]="multiple"
(selectionChange)="selectionChange($event)"
>
selectionChange = (event) => {
let emit: any[] = [];
if (this.multiple) {
emit = this.selectOptions.filter((item) => {
return event.value.find((item2) => item2 === item.value);
});
} else {
emit = [this.selectOptions.find((item) => item.value === event.value)];
}
this.onSelectionChange.emit(emit.map((item) => item.original));
};
而jasmine中使用spies的函数是这样的,我想调用selectionChange函数传递事件作为参数,但是没有成功
it('deverá chamar a função selectionChange', () => {
let select = fixture.debugElement.query(By.css('.mat-select')).nativeElement;
fixture.detectChanges();
spyOn(component,'selectionChange').and.callThrough();
component.selectionChange(select.event);
expect(component.selectionChange).toHaveBeenCalled();
});
我认为你可以在 DebugElement
上利用 triggerEventHandler
。
试试这个:
import { By } from '@angular/platform-browser';
...
it('deverá chamar a função selectionChange', () => {
let select = fixture.debugElement.query(By.css('mat-select'));
const selectSpy = spyOn(component, 'selectionChange').and.callThrough();
// the first argument is the event you want to trigger,
// the 2nd argument is the object that is emitted ($event)
// mock $event however you wish
select.triggerEventHandler('selectionChange', { value: [] });
expect(selectSpy).toHaveBeenCalled();
});