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

Angular独立组件循环依赖导致测试用例执行失败求助

Angular独立组件循环依赖测试报错:Cannot read properties of undefined (reading 'ɵcmp')

问题场景

已通过forwardRef解决Angular独立组件间的循环依赖,组件运行正常,但执行测试用例时触发TypeError: Cannot read properties of undefined (reading 'ɵcmp')错误,即便在TestBed的imports中手动引入关联组件也无法解决。

组件核心代码:

@Component({
    selector: 'my-list',
    templateUrl: './list.component.html',
    styleUrls: ['./list.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: true,
    imports: [forwardRef(() => CustomTypeComponent)]
})

测试核心代码:

beforeEach(async () => {
    await TestBed.configureTestingModule({
        imports: [ListComponent],
        providers: []
    }).compileComponents();
});

解决方案

方案1:测试模块中同步使用forwardRef处理循环依赖

在测试配置的imports中,对循环依赖的组件同样使用forwardRef包裹,确保Angular能正确解析组件引用:

beforeEach(async () => {
    await TestBed.configureTestingModule({
        imports: [
            ListComponent,
            forwardRef(() => CustomTypeComponent)
        ],
        providers: []
    }).compileComponents();
});

方案2:用Mock组件替代循环依赖组件

如果测试不需要依赖关联组件的实际逻辑,可以创建一个极简的Mock组件来替代原组件,彻底规避循环依赖问题:

// 定义Mock组件
@Component({
    selector: 'custom-type', // 与原组件selector一致
    standalone: true,
    template: '<div></div>'
})
class MockCustomTypeComponent {}

// 测试配置中使用Mock组件
beforeEach(async () => {
    await TestBed.configureTestingModule({
        imports: [
            ListComponent,
            MockCustomTypeComponent
        ],
        providers: []
    }).compileComponents();
});

说明:Mock组件只需保持selector与原组件一致,无需实现任何业务逻辑,即可让测试正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:52:39