angular - 如何从测试代码中触发 Angular Material MatSelect 上的 selectionChange 事件
问题描述
我有一个嵌入 Angular MaterialMatSelect
元素的组件。
在我正在编写的测试中,我需要模拟某个选项的选择,并确保selectionChange
与该元素关联的 ObservableMatSelect
实际触发。
到目前为止我的代码是
const mySelect: MatSelect = fixture.nativeElement.querySelector('#mySelect');
mySelect.value = 'new value';
但不幸的是,这并没有发出mySelect.selectionChange
通知,因此我的测试工作。任何关于如何执行此操作的想法都非常受欢迎。
解决方案
我只需访问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);
});
你可以在 这里找到一个堆栈闪电战。
推荐阅读
- excel - 从 ACCESS 查询获取数据时出现 Power Pivot 错误
- python - 来自熊猫数据框的python meshgrid 值
- eclipse - 我的世界锻造模组模组文件夹
- sql - 使用用户输入的日期从表单更新表格
- excel - SharePoint 目录()问题
- kubernetes - 指定每个节点的确切 pod 数量,然后执行映像版本升级
- debugging - Aurelia:从 Chrome 调试控制台调用函数
- angular - 同一组件中的角度5重置图表js栏
- php - 阻止:在 HTTPS 中加载 Laravel CSS 和 JS 时出现混合内容错误
- c# - 修复 VSTO 插件的零 GUID