【问题标题】:How to unit test a component to check a particular component is rendered or not如何对组件进行单元测试以检查特定组件是否已呈现
【发布时间】:2021-01-03 23:44:57
【问题描述】:

我有一个非常简单的自定义组件。我称之为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();
  })
});

它无法正常工作。如果我从模板中删除 &lt;app-navbar&gt;&lt;/app-navbar&gt;,则测试通过前夕。几天前我刚刚开始进行单元测试。请纠正我的错误。

我想提两件事:

  1. 我没有任何 CSS(截至目前)。
  2. 没有 *ngIf 条件,所以应该一直呈现 NavbarComponent

【问题讨论】:

  • 首先,您不应该这样做。 As stated here,对于应用程序组件 单元测试,子组件是不相关的。您应该单独测试每个组件 - 您应该剔除潜艇。其次,你对这个测试所做的只是重新测试 Angular 团队已经测试过的东西——提供/集成组件是框架的责任,所以你不需要测试它。只测试你自己的代码。祝你好运。
  • @RandyCasburn,无论你说什么现在对我来说都更有意义。我做错了。我为此感谢你。实际上,如果我忘记显示app-navbar 怎么办?应该有人来确保它在那里。这就是我的思考过程。请随时纠正我:-)

标签: angular jasmine karma-jasmine


【解决方案1】:

删除app-navbar之后

compiled.querySelector('app-navbar')

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

在这里,您可能想改用toBeTruthy()。使用它,如果您有 app-navbar,您的测试用例将通过,如果您将其删除,您的测试用例将失败。

在 JavaScript 中,有六个 falsy 值:false、0、''、null、undefined 和 NaN。其他一切都是真实的。 Read more here

【讨论】:

  • 此解决方案有效。但我认为我需要更多信息。我正在浏览你分享的链接。谢谢
猜你喜欢
  • 2020-05-19
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 2017-03-25
  • 2014-11-16
  • 2018-12-01
相关资源
最近更新 更多