【问题标题】:Unit Testing select menu change event (not getting updated value)单元测试选择菜单更改事件(未获取更新值)
【发布时间】:2018-03-04 22:11:04
【问题描述】:

试图让我的选择菜单更改事件以正确的值正确触发。它似乎正在触发,但值没有改变。

我的组件中有这个选择菜单:

<select id="seasonDropDown" style="width:200px;height: 36px;" aria-label="Select a Season" (change)="changeSeason($event.target.value)">
        <option *ngFor="let item of seasons" [value]="item.id" [selected]="item.id === seasonId">Season {{item.id}}</option>
    </select>

我有这个更改事件:

  public changeSeason(seasonId: number) {
    this.test = 'blah';  //for testing sake
    console.log('change season ' + seasonId)
    this.seasonId = seasonId;
    this.notify.emit(this.seasonId);
  }

我已经尝试像下面的代码一样对其进行测试,但 commponent.seasonId 永远不会改变其默认值。它应该在 changeSeason 方法中进行更改。我知道该方法正在触发,因为当我测试 expect(component.test).toEqual('blah') 它会通过:

    it('should emit new season on change event', fakeAsync(() => {

        let select = fixture.debugElement.query(By.css('#seasonDropDown')).nativeElement;

        select.value = 2;
        select.selectedValue = 2;

        fixture.detectChanges();

        select.dispatchEvent(new Event('change'));
        tick();

        fixture.detectChanges();


        expect(component.seasonId).toEqual(2);
        //expect(component.test).toEqual('blah');  this will pass so I know the 
        //changeSeason event is actually getting called 
  }));

【问题讨论】:

    标签: angular jasmine karma-jasmine


    【解决方案1】:

    在您的测试中抓取选择元素之前,您应该运行

    fixture.detectChanges();
    

    将 html 元素正确链接到您的组件及其事件处理程序。 看看我在stackblitz 上的复制品。这里只是测试:

    it('should emit new season on change event', () => {
      fixture.detectChanges();
      let select = fixture.debugElement.query(By.css('#seasonDropDown')).nativeElement as HTMLSelectElement;
    
      select.selectedIndex = 1;  // {id:2}
      select.dispatchEvent(new Event('change'));
      fixture.detectChanges();
    
      expect(+component.seasonId).toEqual(2);
      expect(component.test).toBe('blah');
    });
    

    请注意,我使用 HTMLSelectElement 的 selectedIndex 属性来选择第二个选项来模拟更改的选择(与 distachEvent(...) 一起)。

    我希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      相关资源
      最近更新 更多