angular - 如何从测试代码中触发 Angular Material MatSelect 上的 selectionChange 事件

标签 angular angular-material angular-test

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

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

到目前为止我的代码是

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

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

最佳答案

我只需通过 @ViewChild 访问您要测试的组件中的 MatSelect,这样您就可以在单元测试中轻松使用它。

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

You can find a stackblitz here.

关于angular - 如何从测试代码中触发 Angular Material MatSelect 上的 selectionChange 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474470/

相关文章:

performance - 如何测量 Angular2 中的加载时间?

angular - 使用拖放对 mat-tab-group 项目进行排序

带有模拟结构指令的 Angular 测试组件失败

angular - 如何在包含异步逻辑的Angular Component中测试Observable不会发出

Angular Testing 错误 : Can't resolve all parameters for Service:

angular - 如何使用选择快照?

jquery - 在 Angular js 中使用指令或 JQuery 的更好方法

angular - 无法在 Angular 6 中发布

Angular 6 Material - 更改垫选择多个选项中的分隔符

javascript - Angular Material md-card 没有响应