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

Pic*_*cci 1 angular-material angular angular-test

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

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

到目前为止我的代码是

const mySelect: MatSelect = fixture.nativeElement.querySelector('#mySelect');
mySelect.value = 'new value';
Run Code Online (Sandbox Code Playgroud)

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

Fab*_*üng 5

我会简单地访问MatSelect您要测试的组件中的 ,@ViewChild以便您可以轻松地在单元测试中使用它。

/** For testing purposes */
@ViewChild(MatSelect) public matSelect: MatSelect;
Run Code Online (Sandbox Code Playgroud)

在您的测试中,我将通过 选择所需的选项_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);
});
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到一个堆栈闪电战 。


小智 5

一个简单的解决方案是

it('should take the dropdown value and show data ', () => {
let event = {value:25};
debugElement
.query(By.css('.mat-select'))
.triggerEventHandler('selectionChange',event);
fixture.detectChanges();
expect(component.generalLedgerRequest.pageSize).toBe(25);
});
Run Code Online (Sandbox Code Playgroud)