我有一个嵌入 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/