2017-06-06 52 views
2

我有一个顶级组件AppComponent,在它的template属性中,它呈现页面上的<child>元素。 (<child>是另一角分量)。声明在角度单元测试中存在父组件

我需要告诉单元测试忽略<child>元素或以某种方式为测试申报呢?

我实际上并不想在这个测试文件来测试<child>,我将创建一个独立的单元测试文件以验证它的功能。

app.module.ts

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { AppComponent } from './app.component'; 
import { ChildComponent } from './child.component'; 

@NgModule({ 
    bootstrap: [AppComponent], 
    declarations: [AppComponent, ChildComponent], 
    imports: [BrowserModule] 
}) 
export class AppModule { } 

app.component.ts

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'app', 
    template: '<child></child>' 
}) 
export class AppComponent { } 

child.component.ts

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'child', 
    templateUrl: './child.component.html' 
}) 
export class ChildComponent { } 

app.component.spec.ts

import { async, TestBed } from '@angular/core/testing'; 
import { AppComponent } from './app.component'; 
import { ChildComponent } from './child.component'; 

describe('App', (() => { 
    beforeEach(async() => { 
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] }).compileComponents(); 
    })); 
    it('should work',() => { 
    let fixture = TestBed.createComponent(AppComponent); 
    // assert app.component exists 
    }); 
}); 

当我运行单元测试,我得到这个错误:

Error: This test module uses the component ChildComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. in /tmp/karma-typescript-bundle-3142O76A6m7KjQOD.js (line 3929) 

回答

2

的错误指示其他单位(ChildComponent)是参与测试。这个错误是由ChildComponent使用templateUrl,这种部件可能需要调用compileComponents编译它们造成的事实。

由于AppComponenttemplate而不是templateUrl,这使得测试同步,使async帮手必要,也无需使用compileComponents

the guide解释的,

The TestBed.compileComponents method asynchronously compiles all the components configured in the testing module. In this example, the BannerComponent is the only component to compile. When compileComponents completes, the external templates and css files have been "inlined" and TestBed.createComponent can create new instances of BannerComponent synchronously.

单元测试假定仅一个单元被测试,而其他单元被忽略,存根或嘲笑。这可以保持隔离的测试。

由于未声明的元件将导致错误,它们必须被存根:

beforeEach(() => { 
    @Component({ selector: 'child', template: '' }) 
    class DummyChildComponent {} 

    TestBed.configureTestingModule({ declarations: [AppComponent, DummyChildComponent] }); 
    }); 

到虚设部件的替代方案是CUSTOM_ELEMENTS_SCHEMANO_ERRORS_SCHEMA,这不适合于测试,因为任何可能的错误输出可能是有价值的。 custom schema是更重的解决方案。

0

您需要的ChildComponent添加到您的模块:

beforeEach(() => { 
    TestBed.configureTestingModule({ declarations: [AppComponent, ChildComponent] }); 
    }); 
+0

我已经添加'ChildComponent'到'declarations'然后叫'compileComponents()',但它不是检测'compileComponents()'被调用 – bobbyrne01