如何从测试代码中触发 Angular Material MatSelect 上的 selectionChange 事件 [英] How to fire selectionChange event on an Angular Material MatSelect from test code
问题描述
我有一个组件,它嵌入了一个 Angular Material MatSelect
元素.
在我正在编写的测试中,我需要模拟某个选项的选择,并确保与该 MatSelect
元素关联的 selectionChange
Observable 实际触发.
到目前为止我的代码是
const mySelect: MatSelect = fixture.nativeElement.querySelector('#mySelect');mySelect.value = '新值';
但不幸的是,这并没有使 mySelect.selectionChange
通知,因此我的测试工作.非常欢迎有关如何执行此操作的任何想法.
我只需通过 @ViewChild
访问您要测试的组件中的 MatSelect
,这样您就可以在您的单元测试中轻松使用它.
/** 用于测试目的 */@ViewChild(MatSelect) 公共 matSelect: MatSelect;
在您的测试中,我将通过 _selectViaInteraction()
选择所需的选项,这模拟了用户选择了该选项.
it('test selectionChange', () => {//确保 mat-select 具有预期的 mat-optionsconst 选项:MatOption[] = component.matSelect.options.toArray();期望(options.length).toBe(3);期望(选项[0].viewValue).toBe('牛排');期望(选项[1].viewValue).toBe('披萨');期望(选项[2] .viewValue).toBe('Tacos');//在将通过 selectionChange 调用的函数上设置间谍const spy = spyOn(component, 'onChange').and.callThrough();期望(间谍).not.toHaveBeenCalled();//选择选项选项[1]._selectViaInteraction();夹具.detectChanges();//selectionChange 被调用,选项现在被选中期望(间谍).toHaveBeenCalledTimes(1);期望(选项[1].selected).toBe(真);});
<块引用>
你可以找到一个stackblitz此处.
I have a Component which embeds an Angular Material MatSelect
element.
In a test that I am writing, I need to simulate the selection of a certain option and make sure that the selectionChange
Observable associated to that MatSelect
element actually fires.
So far my code is
const mySelect: MatSelect = fixture.nativeElement.querySelector('#mySelect');
mySelect.value = 'new value';
But unfortunately this is not making the mySelect.selectionChange
notify, and therefore my test work. Any idea on how this could be performed is very welcome.
I would simply access the MatSelect
in the component you want to test via @ViewChild
so you can easily use it in your unit test.
/** For testing purposes */
@ViewChild(MatSelect) public matSelect: MatSelect;
And in your test I would select the desired option via _selectViaInteraction()
, this simulates that the option was selected by the user.
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 Material MatSelect 上的 selectionChange 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!