【发布时间】:2020-11-12 10:34:01
【问题描述】:
我对单元测试完全陌生,所以我可能只是在这里做错了一切。一旦我的 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() 失败。这与我的预期相反,我在这里缺少什么?
【问题讨论】:
-
null 在 JS 中不是真的,它是假的。你能详细说明你预期会发生什么吗?您想知道数据网格是否可见吗?另外,toBeTruthy() 中使用的参数没有被使用,通常最好不要传递它。
-
@Bonatti,我预计 toBeTruthy() 会失败,而 toBeNull() 会通过。相反的事情发生了。
-
你应该查询是否没有元素,如果方法返回的数组为空(长度=== 0)
标签: angular jasmine angular-ng-if