如果 angular 2 组件包含另一个组件,如何进行单元测试

How to unit test if an angular 2 component contains another component

我对 angular 2.

很陌生

我有一个组件,它的模板中又包含一些其他组件。

如何编写单元测试来检查我的父组件是否包含其他组件。

提及示例或指导我获取资源会非常有帮助。

MyComponent.ts:

import { Component } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: `<div>
<other-component></other-component>
</div>`
})
export class MyComponent{

}

OtherComponent.ts:

import { Component } from '@angular/core';
@Component({
selector: 'other-component',
templateUrl: `<div>
<h1>Other Component</h1>
</div>`
})
export class OtherComponent{

}

在大多数情况下,您只是在测试外部组件。如果您只想 angular 忽略内部组件,最简单的方法是将 NO_ERRORS_SCHEMA 添加到您的规范中。

从'@angular/core'

导入{NO_ERRORS_SCHEMA}

然后在您的 TestBed.configureTestingModule 中添加行:

模式:[NO_ERRORS_SCHEMA]

然后测试将忽略您没有在组件中导入内部组件的事实 HTML。

如果你想用外部组件测试内部组件,如果你使用 angular-cli,你会看到它们自动为你生成的 component.spec 文件包括一个 declarations 数组,它是 TestBed 配置对象的一部分。所以你所要做的就是导入文件并将组件添加到你的声明中。

所以你上面的例子:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { MyComponent } from './my-component.component';
import { OtherComponent } from './other-component.component';

然后在你的 describe 块中你将有一个 beforeEach

beforeEach(async(() =>{
  TestBed.configureTestingModule({
    declarations: [ MyComponent,
                    OtherComponent ]
  })
  .compileComponent();
})

那么您的组件现在应该可以正确编译,没有错误。如果您想查看整个设置,只需在 angular-cli 中生成一个新项目并查看它生成的规范文档。

测试组件在编译时是否包含其他组件:

  • 注入您正在测试的组件
  • 注入子组件
  • 创建父组件
  • 检测变化
  • 使用querySelectorquerySelectorAll查找子组件

我通常只检查元素是否存在,然后在规范中对单个子组件进行进一步测试。

import { TestBed, async } from '@angular/core/testing';

import { AppComponent } from './app.component';
import { OtherComponent } from './other/other.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        OtherComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it('should have the other component', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('app-other')).not.toBe(null);
  }));
});

使用 querySelector 检查 null 将确定您的组件是否存在。来自 querySelector MDN:

Returns null if no matches are found; otherwise, it returns the first matching element.


如果您想检查同一子组件是否有多个实例,您可以使用 querySelectorAll 并检查 length 属性:

expect(compiled.querySelectorAll('app-other').length).toBeGreaterThan(4);