簡體   English   中英

如何以角度編寫單元測試用例來檢查我的 HTML 頁面中是否存在多個標簽?

[英]How to write unit test cases in angular to check if multiple labels are present in my HTML page?

我對 angular 比較陌生,剛開始用 angular 編寫單元測試用例。 一開始,我只想檢查我的頁面是否有某些帶有某些文本的標簽。

<div class="form-group row">
            <label for="staticEmail" class="col-lg-4 col-form-label">Comments</label>
            <div class="col-lg-8">
                <textarea class="form-control h-85"></textarea>
            </div>
</div>
<div class="form-group row">
            <label class="col-lg-4 col-form-label">City</label>
            <div class="col-lg-8">
                <input class="form-control" type="text">
            </div>
</div>

當我編寫第一個測試用例來檢查是否有一個帶有“評論”的標簽時,它工作正常,但是當為兩個標簽編寫測試用例時..

it('should render Comments in a label tag', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('label').textContent).toContain('Comments');
  });

  it('should render City in a label tag', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('label').textContent).toContain('City');
  });

然后它在第二次測試中失敗並顯示了這個......

預期“評論”包含“城市”。

我也試過這個,但結果是一樣的


it('should render   in an anchor tag', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.query(By.css('label')).nativeElement.innerText;
    expect(compiled).toContain('City');
  });

querySelector方法根據查詢選擇它可以找到的第一個元素。 我想你正在尋找querySelectorAll

expect(compiled.querySelectorAll('label')[1].textContent).toContain('City');

如果您只想測試是否有任何包含City標簽,我想這也適用:

const labels = Array.from(compiled.querySelectorAll('label')).map(
  ({ textContent }) => textContent
);
expect(labels).toContain('City');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM