我有一个非常简单的自定义组件。我称之为NavbarComponent
选择器是 app-navbar
.这是一个非常基本的静态导航栏。我在 app.component.html
上渲染它:
app.component.html
<app-navbar></app-navbar>
<router-outlet></router-outlet>
我正在编写这样的单元测试用例: app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
fdescribe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent,
NavbarComponent
],
}).compileComponents();
}));
it('should create the app', () => {
...
});
it(`should have as title 'my-app'`, () => {
...
});
fit('should display navbar', () => {
const fixture=TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled=fixture.debugElement.nativeElement;
expect(compiled.querySelector('app-navbar')).toBeDefined();
})
});
它不能正常工作。测试通过前夕如果我删除<app-navbar></app-navbar>
从模板。我几天前才开始进行单元测试。请纠正我的错误。
我想提两件事:
- 我没有任何 CSS(截至目前)。
- 没有 *ngIf 条件所以
NavbarComponent
应该一直呈现。
最佳答案
在你移除 app-navbar
之后
compiled.querySelector('app-navbar')
实际上返回 null,这不是未定义的,这就是 toBeDefined 检查通过的原因。
在这里你可能想使用 toBeTruthy()
代替。使用这个,如果你有 app-navbar
,你的测试用例将通过,如果你删除它,你的测试用例将失败。
在 JavaScript 中,有六个假值:false、0、''、null、undefined 和 NaN。其他一切都是真实的。 Read more here
关于angular - 如何对组件进行单元测试以检查特定组件是否呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65551246/