首页 > 解决方案 > 编写 Jasmine 测试以检查 h4 元素的内容

问题描述

我有一个测试,我基本上是在检查 h4 标签。现在在该标签中,我希望能够检查其中给出的内容。我似乎正在编写以下测试,但它一直失败。我不确定我错过了什么或者我的测试写错了:

describe('StatusAppComponent', () => {

  it('should consist of a heading four tag', () => {
   component.showBanner = true;
   fixture.detectChanges();
   const headingElems = fixture.debugElement.query(By.css('h4'));
   expect(headingElems).toHaveText('WARNING')

});

我的html如下:

<div *ngIf="this.showBanner">
  <div class="banner alert">
    <div class="page-section">
  <h4>WARNING</h4>
  {{this.message}}
</div>

标签: angularjasminekarma-jasmine

解决方案


这并不总是必要的,但有时您必须等到视图稳定后才能查询 HTML 元素。

it('should consist of a heading four tag', () => {
  component.showBanner = true;
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    const headingElems = fixture.nativeElement.querySelector('h4');
    expect((headingElems.textContent as string).trim()).toBe('WARNING');
  });
});

推荐阅读