【发布时间】:2017-06-06 16:02:24
【问题描述】:
我有一个顶级组件AppComponent,它在它的template 属性中呈现页面上的<child> 元素。 (<child> 是另一个 Angular 组件)。
我是否需要告诉单元测试忽略<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)
【问题讨论】:
标签: angular unit-testing typescript