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

会有一股神秘感。 提交于 2020-01-03 06:00:48

问题


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.


回答1:


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.




回答2:


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';



回答3:


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);
});


来源:https://stackoverflow.com/questions/54474470/how-to-fire-selectionchange-event-on-an-angular-material-matselect-from-test-cod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!