網站搜尋

javascript - Angular 2 Karma 測試 'component-name' 不是已知的元素


在 AppComponent 中,我在 HTML 代碼中使用了 nav 組件。UI 看起來沒問題。執行 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 的 declarations 部分

@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>

我見過一個類似的問題,但那個問題的答案說我們應該在包含導出的 nav 組件中添加 NgModule,但當我這樣做時會出現編譯錯誤。

還有:app.component.spec.ts

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

答案#1

因為在單元測試中,你希望測試的元件大多時候與應用程式的其他部分隔離,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 {
}

您可以在官方文件中找到更多資訊。

答案#2

你也可以使用 NO_ERRORS_SCHEMA

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

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