2016-11-11 59 views
5

我是相当新的角2。如何单位测试,如果角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{ 

} 

回答

7

为了测试组件,在编译时,含有其他成分:

  • 注入你测试
  • 注入子组件的组件
  • 创建父组件
  • 发现变化
  • 使用querySelectorquerySelectorAll找到子组件

我通常只检查元素是否存在,然后在spec中为每个子组件进行进一步测试。

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将确定您的组件是否存在。从querySelector MDN

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


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

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

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

进口{} 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生成一个新项目,并查看它生成的规格文档。

+1

这并没有真正回答他们有问题。他们希望确保模板中存在的组件不会从外部组件中测试内部组件或独立测试组件。 –