如何测试Angular的SharedModule中是否声明了指定组件?
直接在shared.module.spec.ts中编写以下测试代码即可实现验证:
import { NgModule } from '@angular/core'; import { SharedModule } from './shared.module'; import { NavigationHeaderComponent } from './navigation-header/navigation-header.component'; describe('SharedModule', () => { let moduleDeclarations: any[]; beforeEach(() => { // 提取SharedModule的NgModule装饰器元数据 const ngModuleAnnotation = (SharedModule as any).__annotations__?.find( (anno: any) => anno instanceof NgModule ); moduleDeclarations = ngModuleAnnotation?.declarations || []; }); it('应该在declarations中包含NavigationHeaderComponent', () => { expect(moduleDeclarations).toContain(NavigationHeaderComponent); }); });
代码说明
- Angular会将
@NgModule的配置元数据存储在模块类的__annotations__数组中,通过遍历该数组找到对应的NgModule配置项 - 从配置项中取出
declarations数组,直接断言它包含目标组件NavigationHeaderComponent
内容的提问来源于stack exchange,提问作者Mehrshad Farzaneh
相关产品推荐
相关产品推荐

