Как запустить событие selectionChange на Angular Material MatSelect из тестового кода

У меня есть компонент, в который встроен элемент Angular Material MatSelect.

В тесте, который я пишу, мне нужно смоделировать выбор определенной опции и убедиться, что selectionChange Observable, связанный с этим MatSelect элементом, действительно срабатывает.

Пока мой код

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

Но, к сожалению, это не приводит к уведомлению mySelect.selectionChange, и поэтому мой тест работает. Любая идея о том, как это можно сделать, очень приветствуется.


person Picci    schedule 01.02.2019    source источник


Ответы (3)


Я бы просто получил доступ к MatSelect в компоненте, который вы хотите протестировать, через @ViewChild, чтобы вы могли легко использовать его в своем модульном тесте.

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

И в вашем тесте я бы выбрал желаемый вариант с помощью _selectViaInteraction(), это имитирует, что параметр был выбран пользователем.

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

Вы можете найти stackblitz здесь < / а>.

person Fabian Küng    schedule 01.02.2019

Простое решение -

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);
});
person Farida Anjum    schedule 01.02.2019
comment
Лучшее решение. Работал у меня. - person elonaire; 10.08.2020

Чтобы получить экземпляр MatSelect, вы должны использовать DebugElement на приспособлении и получить доступ к директиве с помощью By.directive:

const mySelect = fixture.debugElement.query(By.directive(MatSelect));
mySelect.componentInstance.value = 'new value';
person Poul Kruijt    schedule 01.02.2019