运行ng-test时遇未识别Angular组件'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.configureTestingModuleblock - Either add
AppNavbarComponentdirectly to thedeclarationsarray, or import the module that contains this component (like aSharedModule) into theimportsarray
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

