Angular 2 业力测试'组件名称'不是已知元素

新手上路,请多包涵

在 AppComponent 中,我在 HTML 代码中使用了导航组件。用户界面看起来不错。执行 ng serve 时没有错误。当我查看应用程序时,控制台中没有错误。

但是当我为我的项目运行 Karma 时,出现错误:

 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 的声明部分

@NgModule({
  declarations: [
    AppComponent,
    CafeComponent,
    ModalComponent,
    NavComponent,
    NewsFeedComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,
    ModalModule.forRoot(),
    ModalModule,
    NgbModule.forRoot(),
    BootstrapModalModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

我在我的 NavComponent 中使用 AppComponent

应用程序组件.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';
}

应用程序组件.html

 <app-nav></app-nav>
<div class="container-fluid">
</div>

我看到了一个类似的问题,但是那个问题的答案是我们应该在导航组件中添加 NgModule,它有一个导出,但是当我这样做时我遇到了编译错误。

还有: app.component.spec.ts

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

原文由 Angela P 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 425
2 个回答

因为在单元测试中,你希望测试的组件主要与应用程序的其他部分隔离开来,所以默认情况下,Angular 不会添加模块的依赖项,如组件、服务等。因此,您需要在测试中手动执行此操作。基本上,您在这里有两个选择:

A) 在测试中声明原始的 NavComponent

 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 {
}

您将在 官方文档 中找到更多信息。

原文由 Kim Kern 发布,翻译遵循 CC BY-SA 4.0 许可协议

您还可以使用 NO_ERRORS_SCHEMA

 describe('AppComponent', () => {
beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [
      AppComponent
    ],
    schemas: [NO_ERRORS_SCHEMA]
  }).compileComponents();
}));

https://2018.ng-conf.org/mocking-dependencies-angular/

原文由 Adrian 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题