'How to create new event for unit testing in Angular 2?

Hi I am writing unit test case for my angular code. I am trying to update textbox in gridview. Below is my gridview code.

<input *ngIf="editing[rowIndex + '-scopevalue']" class="inline-editor" autofocus (blur)="updateValue($event, 'scopevalue', value, rowIndex)" type="text" [value]="value" />

Below function performs update.

 updateValue(event, cell, cellValue, rowIndex) {
        this.editing[rowIndex + '-' + cell] = false;
        this.rows[rowIndex][cell] = event.target.value;
        this.rowsCache[rowIndex][cell] = event.target.value;
        this.scopeEdit = this.rows[rowIndex];
        this.updateScope();
    }

Below unit test case I am writing to check above code.

 it('update scope name value', () => {
        var row = component.rows[0];
        let cell = 'scopevalue';
        let cellValue = row.scopevalue;
        let rowIndex = 0;
        component.updateValue('/bmw', cell, cellValue, rowIndex);
    });

In the above method, first parameter supposed to be event. Can someone help me how to create event? Any help would be appreciated. Thank you



Solution 1:[1]

You can make an hardcoded value of event.target.value and verify in your updateValue function if rowsCache[rowIndex][cell] will have that value.

You can mock an event with a simple object, like this :

const event = { target: { value: 42 }};
component.updateValue(event, cell, cellValue, rowIndex);

Solution 2:[2]

In case your method's argument is typed as an Event object instead:

const mockEvent: Event = <Event><any>{
  target: {
      value: 42      
  }
};
component.updateValue(mockEvent, cell, cellValue, rowIndex);

Solution 3:[3]

You can cast it first to unknown and then to an event like this:

// arrange
const file = {
  name: 'image.png',
  size: 50000,
  type: 'image/png'
} as File;


const mockEvent = {
  target: {
    files: [file]
  }
} as unknown as Event;

// act
component.onInputChange(mockEvent);

// assert
expect(component.files).toEqual([file]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sum NL
Solution 3 Ron Jonk