如何对组件进行单元测试以检查是否渲染了特定组件 [英] How to unit test a component to check a particular component is rendered or not

查看:49
本文介绍了如何对组件进行单元测试以检查是否渲染了特定组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的自定义组件.我称它为NavbarComponent,选择器为app-navbar.这是一个非常基本的静态导航栏.我在app.component.html上渲染它:

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>

我正在编写这样的单元测试用例: app.component.spec.ts

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();
  })
});

它不能正常工作.如果我从模板中删除<app-navbar></app-navbar>,则测试通过.我几天前才刚开始进行单元测试.请纠正我的错误.

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.

我想提两件事:

  1. 我没有任何CSS(截至目前).
  2. 否* ngIf条件,因此应始终呈现NavbarComponent.

推荐答案

删除app-navbar

compiled.querySelector('app-navbar')

实际上返回的是null(不是未定义),这就是toBeDefined检查通过的原因.

actually returns null, which is not undefined, that's why the toBeDefined check is passing.

在这里您可能要使用toBeTruthy().使用此功能,如果您的app-navbar在那里,您的测试用例将通过,如果您删除它,则将失败.

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.

在JavaScript中,有六个伪造的值:false,0,'',null,undefined和NaN.其他一切都是真实的. 在此处了解更多信息

In JavaScript, there are six falsy values: false, 0, '', null, undefined, and NaN. Everything else is truthy. Read more here

这篇关于如何对组件进行单元测试以检查是否渲染了特定组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆