如何从测试代码触发Angular Material MatSelect上的selectionChange事件 [英] How to fire selectionChange event on an Angular Material MatSelect from test code

查看:455
本文介绍了如何从测试代码触发Angular Material MatSelect上的selectionChange事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌入Angular Material MatSelect元素的Component.

I have a Component which embeds an Angular Material MatSelect element.

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

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';

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

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.

推荐答案

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

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;

在测试中,我将通过_selectViaInteraction()选择所需的选项,这模拟了该选项已由用户选择.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆