【问题标题】:Angular testing of mat-checkbox correctly正确地对 mat-checkbox 进行角度测试
【发布时间】:2021-06-05 16:38:51
【问题描述】:

我想知道测试框检查和绑定值更改的正确方法是什么?

这是我的 HTML

     <div>
      <mat-checkbox class="col-md-9 text-right" id="checkid" name="checkid"
                    [checked]="this.isChecked"
                    (change)="this.isChecked = !isChecked">
        CheckBoxLabel
      </mat-checkbox>
    </div>

然后我测试了

const checkboxElem = fixture.debugElement.query(By.css('mat-checkbox')).nativeElement;
expect(checkboxElem.checked).toBeFalsy(); //pass
expect(comp.isChecked).toBeFalsy(); //pass
checkboxElem.click();
fixture.detectChanges();
expect(checkboxElem.checked).toBeTruthy(); //fail
expect(comp.isChecked).toBeTruthy(); //fail

第二个期望总是失败,因为 checkboxElem.checked=false 一直都是。我搜索了大约 5 篇关于这个问题的帖子,并尝试了以下方法,但这些方法都不起作用:

  1. 将此测试设为异步并添加 whenStable(),结果相同
  2. 使用查询By id,结果相同
  3. 将文本放入标签中并由fixture.debugElement.query(By.css('mat-checkbox label')).nativeElement定义元素,结果相同

在调试模式下,我看不到复选框框,只能看到标签。我不确定茉莉花是如何准确单击该元素的。

【问题讨论】:

    标签: angular unit-testing npm checkbox karma-jasmine


    【解决方案1】:

    您是否在importsTestBed.configureTestingModule 数组中导入了MatCheckboxModule?我会导入它来呈现复选框,这样你就不会只看到标签。单独这样做可能会解决它。

    如果这不能解决问题,我仍然会在 imports 数组中导入,我会做 triggerEventHandler

    const checkboxElem = fixture.debugElement.query(By.css('mat-checkbox'));
    expect(checkboxElem.checked).toBeFalsy(); //pass
    expect(comp.isChecked).toBeFalsy(); //pass
    checkboxElem.triggerEventHandler('change', { }); // change this line
    fixture.detectChanges();
    // this bottom line will always fail because checkboxElem is now stale, 
    // you need to grab a new reference
    // expect(checkboxElem.checked).toBeTruthy(); //fail
    const newCheckboxElem = fixture.debugElement.query(By.css('mat-checkbox')).nativeElement;
    expect(newCheckboxElem.checked).toBeTruthy();
    expect(comp.isChecked).toBeTruthy(); //fail
    

    详细了解triggerEventHandlerhere

    【讨论】:

    • 感谢您的快速回复,您的链接很有帮助!但是我导入了 MatCheckModule 并尝试使用triggerEventHandler,但得到了错误:TypeError: checkboxElem.triggerEventHandler is not a function。
    • 糟糕,我认为应该是 fixture.debugElement.query(By.css('mat-checkbox'))(没有 nativeElement,第一行已更改)。我已经编辑了我的答案。
    【解决方案2】:

    最后我尝试了这个并且它有效。使用 dispatchEvent 允许单击复选框并且选中状态变为 true。这是@AliF50 的triggerEventHandler 链接中的建议之一。

    const checkboxElem = fixture.debugElement.query(By.css('mat-checkbox')).nativeElement;
    expect(checkboxElem.checked).toBeFalsy();
    
    checkboxElem.dispatchEvent(new Event('change'));
    fixture.detectChanges();
    expect(checkboxElem.checked).toBeTruthy();
    

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2010-09-23
      • 2014-01-30
      • 2011-02-02
      相关资源
      最近更新 更多