Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Unit Testing: Mocking a MatSelectChange event

Description: I am writing unit tests for the following function:

updateUserStatus(event: MatSelectChange | any, reportID: number) {
    const matOption = (event.source.selected as MatOption);
    const option = matOption.value;
    this.setUserActions(reportID, option.id);
}

Test Spec

it('should test updateUserStatus', () => {
    spyOn(component, 'updateUserStatus').and.callThrough();
    spyOn(component, 'setUserActions').and.callFake(() => {});
    component.updateUserStatus({{MOCK_EVENT_HERE}}, 123456);
    expect(component.updateUserStatus).toHaveBeenCalledTimes(1);
    expect(component.setUserActions).toHaveBeenCalledTimes(1);
});

Problem: I am finding it hard to mock the 'event' argument which is an instance of 'MatSelectChange'.

What have I tried so far?

1. Copying 'event' value from browser console

This gives me a:

Uncaught TypeError: Converting circular structure to JSON.

2. Create a new MatSelectChange instance

The 'MatSelect' constructor requires 12-13 arguments oh my!. Don't know how to instantiate:

const selectChange = new MatSelectChange(new MatSelect(), 'Value');

If any other detail is missing, please let me know if that will help in understanding it better.

like image 339
Pradeep Vig Avatar asked Sep 14 '25 18:09

Pradeep Vig


1 Answers

If you're still stuck on this, I would just send a plain JavaScript object.

Try:

it('should test updateUserStatus', () => {
    spyOn(component, 'updateUserStatus').and.callThrough();
    spyOn(component, 'setUserActions').and.callFake(() => {});
    event.source.selected
    const mockMatSelectChange = {
      event: {
        source: {
         selected: {
           value: {
             id: '123', // mock ID to whatever it should be
           }
         } 
       }
      }
    };
    component.updateUserStatus(mockMatSelectedChange, 123456);
    expect(component.updateUserStatus).toHaveBeenCalledTimes(1);
    expect(component.setUserActions).toHaveBeenCalledTimes(1);
});
like image 192
AliF50 Avatar answered Sep 16 '25 08:09

AliF50