在/ src / app / book中,我有以下文件 - book.component.ts,book.module.ts,book.component.html,book-routing.module.ts,addbook.component.html,addbook .component.ts
我的book.component.html包含以下代码;
<button class="btn btn-outline-success" (click)="addButton()">Add Book</button>
<div *ngIf="toggleFlag">
<app-addbook></app-addbook>
</div>
我的book.module.ts包含以下代码:
@NgModule({
imports: [
CommonModule,
ReactiveFormsModule,
BookRoutingModule
],
declarations: [
BookComponent,
AddbookComponent
],
providers: [BookService]
})
export class BookModule { }
我的book-routing.module.ts包含以下代码:
const bookRoutes: Routes = [
{
path: 'addbook',
component: AddbookComponent,
canActivate: [AuthGuardService],
}
];
@NgModule({
imports: [
RouterModule.forChild(bookRoutes)
],
exports: [
RouterModule
]
})
export class BookRoutingModule {
}
应用程序运行良好;但是,当我运行命令ng test
时,它会告诉我:
失败:模板解析错误:&#39; app-addbook&#39;不是一个已知元素:
如果&#39; app-addbook&#39;是一个Angular组件,然后验证它是否是该模块的一部分。
- 醇>
如果&#39; app-addbook&#39;是一个Web组件,然后添加&#39; CUSTOM_ELEMENTS_SCHEMA&#39;到了&#39; @ NgModule.schemas&#39;这个组件 压制此消息。 (&#34; btn btn-outline-success&#34; (点击)=&#34; addButton()&#34;&gt;添加图书
<div *ngIf="toggleFlag">
[错误 - &gt;]<app-addbook></app-addbook>
</div>
更新---
我的 book.component.spec.ts 如下:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BookComponent } from './book.component';
describe('BookComponent', () => {
let component: BookComponent;
let fixture: ComponentFixture<BookComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BookComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(BookComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
答案 0 :(得分:2)
首先在 book.component 规范文件的AddbookComponent
部分添加declarations
。见下文。
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {AddbookComponent} from './addbook.component';
import { BookComponent } from './book.component';
describe('BookComponent', () => {
let component: BookComponent;
let fixture: ComponentFixture<BookComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BookComponent, AddbookComponent ]
})
.compileComponents();
}));
...
});
在排除故障时,您很可能需要在规范中添加其他内容。您已在应用程序中更改了内容,因此需要更新规范。
Here是Angular测试技术的优秀资源。