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

Angular测试报错:'mat-card-title'不是已知元素问题咨询

搞定Angular测试里的'mat-card-title'未知元素错误

嘿,我来帮你分析解决这个问题!你运行ng test时碰到的这个模板解析错误,其实是测试环境没找到对应的Angular Material组件依赖,我看了你的模块代码,给你几个具体的解决步骤:

为啥会出这个错?

从你贴的代码来看,AngularMaterialModule已经正确导入并导出了MatCardModule,AppModule也引入了这个共享模块,所以应用运行时可能没问题,但测试时每个组件是单独跑的,测试模块没加载这些依赖。另外我还注意到你的AppModule里漏声明了不少组件,这也可能是诱因之一。

具体怎么修?

第一步:给组件的测试模块加依赖

打开用了mat-card-title的组件(比如HeroDetailComponent)对应的.spec.ts文件,在测试模块的imports里加上AngularMaterialModule,比如:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HeroDetailComponent } from './hero-detail.component';
import { AngularMaterialModule } from '../angular-material/angular-material.module';

describe('HeroDetailComponent', () => {
  let component: HeroDetailComponent;
  let fixture: ComponentFixture<HeroDetailComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ HeroDetailComponent ],
      imports: [ AngularMaterialModule ] // 把共享模块加进来
    })
    .compileComponents();
  });

  // 剩下的测试代码不变
});

第二步:把漏声明的组件加到AppModule里

我看到你的AppModule的declarations数组里只有AppComponent和LoginComponent,但你开发的HeroDetailComponent、HeroesListComponent这些组件都没在里面!如果这些组件是直接在根模块下用的,得把它们都加进去:

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    HeroesListComponent,
    HeroDetailComponent,
    HeroSearchComponent,
    HeroTableComponent,
    NavbarHeroesComponent,
    AddHeroesComponent,
    HeroGridComponent
  ],
  // 其他配置不变
})
export class AppModule { }

要是这些组件属于某个特性模块,那记得让那个特性模块导入AngularMaterialModule,再把特性模块加到AppModule的imports里就行。

临时方案(不推荐)

要是你只是想先跳过这个提示(不建议长期用),可以在测试模块里加CUSTOM_ELEMENTS_SCHEMA屏蔽检查:

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

await TestBed.configureTestingModule({
  declarations: [ HeroDetailComponent ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})

不过这个只是绕开错误,没解决根本问题,还是优先用前两个方案哈。

验证一下

改完之后再跑ng test,这个错误应该就消失啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:44:29