首页 > 解决方案 > 如何从测试代码中触发 Angular Material MatSelect 上的 selectionChange 事件

问题描述

我有一个嵌入 Angular MaterialMatSelect元素的组件。

在我正在编写的测试中,我需要模拟某个选项的选择,并确保selectionChange与该元素关联的 ObservableMatSelect实际触发。

到目前为止我的代码是

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

但不幸的是,这并没有发出mySelect.selectionChange通知,因此我的测试工作。任何关于如何执行此操作的想法都非常受欢迎。

标签: angularangular-materialangular-test

解决方案


我只需访问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);
});

你可以在 这里找到一个堆栈闪电战。


推荐阅读