How to unit test a component to check a particular component is rendered or not

僤鯓⒐⒋嵵緔 提交于 2021-01-28 14:22:36

问题


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:

  1. I don't have any css (as of now).
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!