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

Angular自定义库组件测试报错:TypeError: Cannot read 'ngModule' of null

解决Angular库组件测试报错:TypeError: Cannot read properties of null (reading 'ngModule')

问题描述

我使用Jasmine和TestBed测试CLI生成的自定义Angular库组件AComponent(未添加任何额外代码),运行单元测试时触发以下错误:

TypeError: Cannot read properties of null (reading 'ngModule')
Jasmine界面也同步显示该报错。

相关代码文件如下:

app.component.spec.ts

import {ComponentFixture, TestBed} from '@angular/core/testing';

import {AComponent} from './a.component';

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

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            declarations: [AComponent],
        }).compileComponents();

        fixture = TestBed.createComponent(AComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

ng-package.json

{
    "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
    "dest": "../../dist/mehrshad-core",
    "lib": {
        "entryFile": "src/public-api.ts"
    }
}

package.json

{
    "name": "mehrshad-core",
    "version": "0.0.23",
    "peerDependencies": {
        "@angular/common": "^15.2.0",
        "@angular/core": "^15.2.0"
    },
    "dependencies": {
        "@sweetalert2/ngx-sweetalert2": "^12.2.0",
        "sweetalert2": "^11.7.28",
        "tslib": "^2.3.0"
    },
    "sideEffects": false
}

解决方案

1. 确保组件关联到NgModule

Angular库中的组件必须归属到某个NgModule,TestBed才能正确识别组件元数据:

  • 创建或修改组件对应的NgModule(比如a.module.ts):
import { NgModule } from '@angular/core';
import { AComponent } from './a.component';

@NgModule({
  declarations: [AComponent],
  exports: [AComponent] // 若需对外暴露组件则添加
})
export class AModule { }
  • 修改测试文件,导入该NgModule而非直接声明组件:
import { AModule } from './a.module'; // 新增导入

// ...

beforeEach(async () => {
    await TestBed.configureTestingModule({
        imports: [AModule], // 替换原declarations配置
    }).compileComponents();

    // 后续代码保持不变
});

2. 匹配ng-packagr与Angular版本

Angular 15需要搭配^15.x.x版本的ng-packagr,检查根目录package.json中的依赖版本,不匹配则执行更新:

npm install ng-packagr@^15.2.0 --save-dev

3. 清理并重建环境

删除旧依赖和构建产物,重新安装并构建:

rm -rf node_modules dist
npm install
npm run build

之后再运行测试:

ng test

4. 检查public-api.ts导出配置

确保src/public-api.ts中正确导出组件和模块:

export * from './lib/a.component';
export * from './lib/a.module';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:54:55