TypeError: event.target.getAttribute is not a function in Karma Jasmine

TypeError: event.target.getAttribute is not a function in Karma Jasmine

Angular component.ts 文件有这个方法,在输入字段模糊时被调用。

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 is not a function

单元测试代码:

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 问题!!

谢谢

您需要将 attribute/function 添加到 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 所需的所有模拟。