问题
I've a very simple custom component. I call it NavbarComponent
and the selector is app-navbar
. It is a very basic static navbar. I'm rendering it on app.component.html
:
app.component.html
<app-navbar></app-navbar>
<router-outlet></router-outlet>
I'm writing a unit test case like this: 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();
})
});
It's not working properly. The test is passed eve If i remove <app-navbar></app-navbar>
from the template. I've just started with Unit testing few days ago. Please correct my mistake.
2 things I would like to mention:
- I don't have any css (as of now).
- No *ngIf condition so
NavbarComponent
should be rendered all the time.
回答1:
After you have removed app-navbar
compiled.querySelector('app-navbar')
actually returns null, which is not undefined, that's why the toBeDefined check is passing.
Here you may want to use toBeTruthy()
instead. Using this, your test case will pass if you have the app-navbar
there and will fail if you remove it.
In JavaScript, there are six falsy values: false, 0, '', null, undefined, and NaN. Everything else is truthy. Read more here
来源:https://stackoverflow.com/questions/65551246/how-to-unit-test-a-component-to-check-a-particular-component-is-rendered-or-not