Angular 2 Karma Test 'component-name' 不是已知元素
在 AppComponent 中,我在 HTML 代码中使用了导航组件.用户界面看起来不错.执行 ng serve 时没有错误.当我查看应用程序时,控制台中没有错误.
In the AppComponent, I'm using the nav component in the HTML code. The UI looks fine. No errors when doing ng serve. and no errors in console when I look at the app.
但是当我为我的项目运行 Karma 时,出现了错误:
But when I ran Karma for my project, there is an error:
Failed: Template parse errors:
'app-nav' is not a known element:
1. If 'app-nav' is an Angular component, then verify that it is part of this module.
2. If 'app-nav' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
在我的 app.module.ts 中:
有:
import { NavComponent } from './nav/nav.component';
它也在 NgModule 的声明部分
It is also in the declarations part of NgModule
@NgModule({
declarations: [
AppComponent,
CafeComponent,
ModalComponent,
NavComponent,
NewsFeedComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
ModalModule.forRoot(),
ModalModule,
NgbModule.forRoot(),
BootstrapModalModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
我在 AppComponent
app.component.ts
import { Component, ViewContainerRef } from '@angular/core';
import { Overlay } from 'angular2-modal';
import { Modal } from 'angular2-modal/plugins/bootstrap';
import { NavComponent } from './nav/nav.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angela';
}
app.component.html
<app-nav></app-nav>
<div class="container-fluid">
</div>
我看到了一个类似的问题,但该问题的答案说我们应该在具有导出功能的导航组件中添加 NgModule,但是当我这样做时出现编译错误.
I have seen a similar question, but the answer in that question says we should add NgModule in the nav component that has a export in that, but I'm getting compile error when I do that.
还有:app.component.spec.ts
import {NavComponent} from './nav/nav.component';
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
推荐答案
因为在单元测试中您希望测试与应用程序的其他部分大部分隔离的组件,默认情况下,Angular 不会添加您的模块的依赖项,如组件、服务等.因此,您需要在测试中手动执行此操作.基本上,您有两种选择:
Because in unit tests you want to test the component mostly isolated from other parts of your application, Angular won't add your module's dependencies like components, services, etc. by default. So you need to do that manually in your tests. Basically, you have two options here:
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
NavComponent
]
}).compileComponents();
}));
B) 模拟 NavComponent
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
MockNavComponent
]
}).compileComponents();
}));
// it(...) test cases
});
@Component({
selector: 'app-nav',
template: ''
})
class MockNavComponent {
}
您可以在官方文档中找到更多信息.
You'll find more information in the official documentation.
相关文章