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

时间:2016-11-11 04:29:43

标签: angular karma-jasmine angular2-testing

我对棱角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{

}

2 个答案:

答案 0 :(得分:21)

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

  • 注入您正在测试的组件
  • 注入子组件
  • 创建父组件
  • 检测更改
  • 使用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

  

如果未找到匹配项,则返回null;否则,它返回第一个   匹配元素。

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

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

答案 1 :(得分:11)

在大多数情况下,您只是测试外部组件。如果您只想让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中生成一个新项目,然后查看它生成的规范文档。