You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行ng-test时遇未识别Angular组件'app-navbar'及模板解析错误求助

解决Angular测试中'Unrecognized angular component "app-navbar"'的问题

Hey, I've run into this exact issue before with Angular tests! The problem boils down to the DynamicTestModule not recognizing your app-navbar element. Here's how to fix it depending on what kind of element it is:

1. If app-navbar is your own Angular component

You need to register the component (or its parent module) in your test configuration:

  • Open your component's test file (usually app.component.spec.ts)
  • Locate the TestBed.configureTestingModule block
  • Either add AppNavbarComponent directly to the declarations array, or import the module that contains this component (like a SharedModule) into the imports array

Example code:

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [
      AppComponent,
      AppNavbarComponent // Add your navbar component here
    ],
    // If your navbar lives in a SharedModule, replace declarations with this:
    // imports: [SharedModule]
  }).compileComponents();
});

Important note: If you're importing a module, make sure that module exports AppNavbarComponent—otherwise the test module still won't have access to it.

2. If app-navbar is a third-party Web Component

If this is a custom element (like from a UI library that uses Web Components), you need to add CUSTOM_ELEMENTS_SCHEMA to your test module to tell Angular to ignore unknown elements:

Example code:

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [AppComponent],
    schemas: [CUSTOM_ELEMENTS_SCHEMA] // Add this to suppress the error
  }).compileComponents();
});

After making either of these changes, run ng test again and the template parsing error should be gone!

内容的提问来源于stack exchange,提问作者B Narasimha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:30:33