TypeError:event.target.getAttribute不是Karma Jasmine中的函数



Angular component.ts文件有一个方法,该方法在输入字段中的blur上被调用。

dataCapture(event, fieldValue) {
if (event.target.value !== fieldValue) {
const controlNameForValidation = event.target.getAttribute('formControlName');
const altValue = event.target.alt; // event.target.alt;
const labelNameForAction = event.target.getAttribute('aria-label');
...
}

输入字段为:

<input (blur)="dataCapture($event, initialData.firstName)" aria-label="firstName" type="text" id="firstName" name="firstName" />

我正试图为上面的方法编写如下的单元测试,但即使在尝试了不同的模拟值后,也会得到

TypeError:event.target.getAttribute不是函数

单元测试代码:

it('should test dataCapture', () => {
component.initialData = initialData;
fixture.detectChanges();
const mockEvent: Event = {
target: {
value: 'tes',
type:'text', id:'firstNameEmp', name:'firstName',
'aria-Label': 'sectionOne.firstName',
formControlName: 'firstName'
},
stopPropagation: ( ( e: any ) => { /**/ }) as any,
preventDefault: ( ( e: any ) => { /**/ }) as any,
} as any as Event;
component.dataCapture(mockEvent, initialData.firstName);
expect(component).toBeTruthy(); //expect doesn't matter this time
}

也尝试了许多其他的嘲讽方法,但最终的结果总是一样的。

有人能指出正确的嘲笑方式来解决event.target.getAttribute问题吗!!

感谢

您需要将属性/函数添加到mockEvent的target属性中。

const mockEvent: Event = {
target: {
value: 'tes',
type:'text', id:'firstNameEmp', name:'firstName',
'aria-Label': 'sectionOne.firstName',
formControlName: 'firstName',
// !! add getAttribute here !!
getAttribute: () => null,
},
stopPropagation: ( ( e: any ) => { /**/ }) as any,
preventDefault: ( ( e: any ) => { /**/ }) as any,
} as any as Even

确保mockEvent具有方法dataCapture所需的所有模拟内容。