如何使用 Jasmine 测试显示 html 元素的复选框

How to test with Jasmine a checkbox that shows an html element

我是 Angular 测试的新手,我想我有一个愚蠢的问题,但尽管有很多教程和指南,我还是找不到有效的解决方案。

我有一个复选框,当它被选中时它应该显示 div,我想用 Jasmine 测试它。 这是我的 HTML:

<div>
  Check this! <input #cb type="checkbox" (change)="1" id="checkboxToTest"/>

  <div id="divRevealed" *ngIf="cb.checked">Hello!</div>

</div>

这是规范文件中的代码:

  it('should test checkbox', () => {
    const dElement = fixture.debugElement;
    const nElement = dElement.nativeElement;
    const checkBoxElement = nElement.querySelector('#checkboxToTest');
    const box = nElement.querySelector('#divRevealed');

    checkBoxElement.click();

    expect(checkBoxElement.checked);

    fixture.detectChanges();

    expect(box).toBeTruthy();
  });

显然,如果我删除 HTML...

中的 *ngIf 语句,测试毫无问题地通过了

但为什么它不起作用?

感谢您的帮助!

必须在单击 元素复选框后检测组件:

it('should test checkbox', waitForAsync(() => {
    const dElement = fixture.debugElement;
    const nElement = dElement.nativeElement;
    const checkBoxElement = nElement.querySelector('#checkboxToTest');

    checkBoxElement.click();
    fixture.detectChanges();

    expect(checkBoxElement.checked);

    fixture.detectChanges();

    const box = nElement.querySelector('#divRevealed');

    expect(box).toBeDefined();
  }));