我对单元测试完全陌生,所以我可能在这里做错了所有的事情。我使用*ngIf在GET请求完成后显示来自DevExpress的数据网格,并尝试使用Jasmine测试验证它只在我的*ngIf条件设置为真时显示。
我的网格的截断版本:
<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()失败。这与我的预期相反,我在这里遗漏了什么?
发布于 2020-07-23 03:51:32
你的queryAll选择的元素在超文本标记语言中的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();
});query查找第一个匹配项,并且只查找一个元素。
发布于 2020-07-23 03:56:29
queryAll()方法返回一个包含信息的数组。
如果您希望没有这样的元素,您可以使用expect(thing).toHaveLength(0)
当定义不存在这样的元素时,您还可以使用query() (这将返回第一个匹配项,并期望其为空
https://stackoverflow.com/questions/63041732
复制相似问题