How to fire selectionChange event on an Angular Material MatSelect from test code
Asked Answered
S

3

4

I have a Component which embeds an Angular Material MatSelect element.

In a test that I am writing, I need to simulate the selection of a certain option and make sure that the selectionChange Observable associated to that MatSelect element actually fires.

So far my code is

const mySelect: MatSelect = fixture.nativeElement.querySelector('#mySelect');
mySelect.value = 'new value';

But unfortunately this is not making the mySelect.selectionChange notify, and therefore my test work. Any idea on how this could be performed is very welcome.

Studley answered 1/2, 2019 at 7:1 Comment(0)
C
6

I would simply access the MatSelect in the component you want to test via @ViewChild so you can easily use it in your unit test.

/** For testing purposes */
@ViewChild(MatSelect) public matSelect: MatSelect;

And in your test I would select the desired option via _selectViaInteraction(), this simulates that the option was selected by the user.

it('test selectionChange', () => {    
  // make sure the mat-select has the expected mat-options
  const options: MatOption[] = component.matSelect.options.toArray();
  expect(options.length).toBe(3);
  expect(options[0].viewValue).toBe('Steak');
  expect(options[1].viewValue).toBe('Pizza');
  expect(options[2].viewValue).toBe('Tacos');

  // set up a spy on the function that will be invoked via selectionChange
  const spy = spyOn(component, 'onChange').and.callThrough();
  expect(spy).not.toHaveBeenCalled();

  // select the option
  options[1]._selectViaInteraction();
  fixture.detectChanges();

  // selectionChange was called and the option is now selected    
  expect(spy).toHaveBeenCalledTimes(1);
  expect(options[1].selected).toBe(true);
});

You can find a stackblitz here.

Cawnpore answered 1/2, 2019 at 7:38 Comment(0)
H
5

A simple solution is

it('should take the dropdown value and show data ', () => {
let event = {value:25};
debugElement
.query(By.css('.mat-select'))
.triggerEventHandler('selectionChange',event);
fixture.detectChanges();
expect(component.generalLedgerRequest.pageSize).toBe(25);
});
Halonna answered 1/2, 2019 at 10:12 Comment(1)
Best solution. Worked for me.Weight
T
1

To get the MatSelect instance, you have to use the DebugElement on the fixture and access the directive using By.directive:

const mySelect = fixture.debugElement.query(By.directive(MatSelect));
mySelect.componentInstance.value = 'new value';
Truce answered 1/2, 2019 at 7:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.