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

如何测试Angular的SharedModule中是否声明了指定组件?

验证SharedModule的declarations包含NavigationHeaderComponent的Karma测试用例

直接在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:45:34