首页 文章

Angular 2 Karma Test 'component-name'不是已知元素

提问于
浏览
47

在AppComponent中,我在HTML代码中使用nav组件 . 用户界面看起来很好 . 做服务时没有错误 . 当我查看应用程序时,控制台中没有错误 .

但是当我为我的项目运行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]
})

我在 AppComponent 中使用 NavComponent

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,其中有导出,但是当我这样做时我遇到了编译错误 .

还有: app.component.spec.ts

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

2 回答

  • 3

    因为在单元测试中,您希望测试主要与应用程序的其他部分隔离的组件,所以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 {
    }
    

    您可以在official documentation中找到更多信息 .

  • 75

    你也可以用 NO_ERRORS_SCHEMA

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

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

相关问题