元素仍然被定义,即使*ngIf是false Jasmine单元测试Angular



我对单元测试完全陌生,所以我可能只是做错了所有事情。当我的GET请求完成后,我使用*ngIf显示DevExpress的数据网格,并且我试图用Jasmine测试验证它只在我的*ngIf条件设置为true时显示。

我的网格的截断版本:


    <dx-data-grid #grid *ngIf="!loading">
        ...
    </dx-data-grid>

和我的.spec文件:

import { ApplicationsComponent } from "./applications.component";
import { ComponentFixture, async, TestBed } from "@angular/core/testing";
import { RouterTestingModule } from "@angular/router/testing";
import { HttpClientTestingModule } from "@angular/common/http/testing";
import { DxDataGridModule } from "devextreme-angular";
import { DebugElement } from "@angular/core";
import { By } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
describe("ApplicationPocComponent", () => {
  let component: ApplicationsComponent;
  let fixture: ComponentFixture<ApplicationsComponent>;
  let el: DebugElement;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ApplicationsComponent],
      imports: [RouterTestingModule, HttpClientTestingModule, DxDataGridModule, CommonModule ],
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(ApplicationsComponent);
        component = fixture.componentInstance;
        el = fixture.debugElement; 
      });
  }));
  it("should create applications component", () => {
    expect(component).toBeTruthy();
  });
  it("should display the data grid", () => { 
    component.loading = true; 
    fixture.detectChanges(); 
    const dataGrid = el.queryAll(By.css("#grid")); 
    expect(dataGrid).toBeTruthy("Datagrid not created"); 
    expect(dataGrid).toBeNull("Datagrid is created"); 
  })
});

我的第一个断言expect(dataGrid).toBeTruthy()成功,而断言.toBeNull()失败。这与我的预期相反,我在这里错过了什么?

您的queryAll正在选择HTML中id为grid的元素,我敢打赌这些元素不存在。queryAll查询整个DOM并将元素作为数组返回,如果没有找到任何内容则返回一个空数组。JavaScript中的空数组是真实的;

 it("should display the data grid", () => { 
    component.loading = true; 
    fixture.detectChanges(); 
    const dataGrid = el.queryAll(By.css("#grid")); 
    console.log(dataGrid); // See if you see [] here.
    expect(dataGrid).toBeTruthy("Datagrid not created"); 
    expect(dataGrid).toBeNull("Datagrid is created"); 
  });

要修复它,可以使用query,但如果要使用queryAll,请检查返回数组的长度。

 it("should NOT display the data grid when loading", () => { 
    component.loading = true; 
    fixture.detectChanges(); 
    const dataGrid = el.queryAll(By.css("dx-data-grid")); // change to dx-data-grid here
    console.log(dataGrid); // See if you see [] here, should still see [] here
    expect(dataGrid.length).toBe(0);
  });

我会做什么:

 it("should NOT display the data grid when loading", () => { 
    component.loading = true; 
    fixture.detectChanges(); 
    const dataGrid = el.query(By.css("dx-data-grid")); // change to dx-data-grid here and query
    expect(dataGrid).toBeNull();
  });

CCD_ 7查找第一个匹配并且仅查找一个元素。

方法queryAll((返回一个数组,其中包含信息。

如果你希望没有这样的元素,你可以expect(thing).toHaveLength(0)

当定义不存在这样的元素时,您也可以query(((它将返回第一个匹配,并期望它为空

最新更新