Angular component.ts file has this method that is getting called on blur from input field.
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');
...
}
The input field is as:
<input (blur)="dataCapture($event, initialData.firstName)" aria-label="firstName" type="text" id="firstName" name="firstName" />
And I am trying to write unit test for the above method as follow but even after trying different mock values, getting
TypeError: event.target.getAttribute is not a function
unit test code :
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
}
Also tried many other mocking methods, but end result is always same.
Can someone point the right way of mocking to resolve event.target.getAttribute issue!!
Thanks
CodePudding user response:
You need to add the attribute/function to the target
property of the mockEvent.
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
Make sure the mockEvent
has everything mocked required for the method dataCapture
.