[英]How to unit test a component to check a particular component is rendered or not
我有一個非常簡單的自定義組件。 我稱之為NavbarComponent
,選擇器是app-navbar
。 這是一個非常基本的 static 導航欄。 我在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>
,則測試通過前夕。 幾天前我剛剛開始進行單元測試。 請糾正我的錯誤。
我想提兩件事:
NavbarComponent
應該一直呈現。刪除app-navbar
后
compiled.querySelector('app-navbar')
實際上返回 null,這不是未定義的,這就是 toBeDefined 檢查通過的原因。
在這里,您可能想改用toBeTruthy()
。 使用它,如果你有app-navbar
,你的測試用例將通過,如果你刪除它,你的測試用例將失敗。
在 JavaScript 中,有六個 falsy 值:false、0、''、null、undefined 和 NaN。 其他一切都是真實的。 在這里閱讀更多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.