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

Angular Jest测试:ng-container内Mock变量致组件查找失败问题

问题:Angular Jest单元测试中ng-container内组件查找失败

组件HTML代码

<ng-container *ngVar="personFacade.personInfo$ | async as personInfo">
 @if (personInfo.active){
  <childcomponent1></childcomponent1>
 }@else 
{ <childcomponent2></childcomponent2>
}
</ng-container>

逻辑:根据personInfo.active的值渲染对应子组件。

已实现的Mock代码

function mockPersonInfo(): jest.Mock<any, any> {
  return MockInstance(PersonFacade, 'personInfo$', jest.fn(), 'get').mockReturnValue(of(personInfo));
}

测试代码(验证active为false时)

it('should show only childcomponent2', () => {
 mockPersonInfo();
 component = fixture.point.componentInstance;
 fixture.detectChanges();

  const childcomponent1 = ngMocks.find('childcomponent1');
  expect(childcomponent1).toBeFalsy();
});

问题现象

执行测试时报错:Cannot find an element via ngMocks.find('childcomponent1'),但将childcomponent1移出ng-container后可正常查找,怀疑ng-container内的数据Mock存在问题。


解决方法

1. 确认Mock的personInfo数据正确设置active为false

检查你定义的personInfo变量,确保active字段确实被设为false。如果这个值错误,childcomponent1会被渲染,而ngMocks.find默认找不到元素时会直接抛出异常,而非返回null。

2. 用ngMocks.findOptional替代ngMocks.find

ngMocks.find找不到元素时会抛出错误,ngMocks.findOptional会返回null/undefined,更适合验证元素不存在的场景:

const childcomponent1 = ngMocks.findOptional('childcomponent1');
expect(childcomponent1).toBeFalsy();

3. 等待异步数据流处理完成

因为使用了async管道,需要等待异步任务完成后再断言,通过fixture.whenStable()实现:

it('should show only childcomponent2', async () => {
 mockPersonInfo();
 component = fixture.point.componentInstance;
 fixture.detectChanges();
 await fixture.whenStable(); // 等待async管道处理完毕

 const childcomponent1 = ngMocks.findOptional('childcomponent1');
 expect(childcomponent1).toBeFalsy();
 const childcomponent2 = ngMocks.find('childcomponent2');
 expect(childcomponent2).toBeTruthy();
});

4. 检查ngVar指令的配置

如果ngVar是自定义或第三方指令,需确保测试模块中已导入对应模块,或对该指令进行了Mock。否则ng-container内的逻辑无法生效,组件无法正确渲染。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 15:40:10