【问题标题】:How to fire selectionChange event on an Angular Material MatSelect from test code如何从测试代码中触发 Angular Material MatSelect 上的 selectionChange 事件
【发布时间】:2019-06-25 17:36:45
【问题描述】:

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

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

到目前为止我的代码是

const mySelect: MatSelect = fixture.nativeElement.querySelector('#mySelect');
mySelect.value = 'new value';

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

【问题讨论】:

    标签: angular angular-material angular-test


    【解决方案1】:

    我只需通过@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);
    });
    

    你可以找到一个堆栈闪电战 here.

    【讨论】:

      【解决方案2】:

      一个简单的解决方案是

      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);
      });
      

      【讨论】:

      • 最佳解决方案。为我工作。
      【解决方案3】:

      要获取MatSelect 实例,您必须在夹具上使用DebugElement 并使用By.directive 访问指令:

      const mySelect = fixture.debugElement.query(By.directive(MatSelect));
      mySelect.componentInstance.value = 'new value';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        • 1970-01-01
        • 2015-07-28
        • 2014-08-15
        • 2013-12-14
        • 2019-05-17
        • 2011-05-30
        相关资源
        最近更新 更多