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

如何对使用Ngrx LetDirective的组件进行单元测试?

问题:Ngrx LetDirective在Jest单元测试中无法渲染内容

我使用Ngrx LetDirective在组件中消费Observable结果,组件代码如下:

myComponent.component.html

<ng-container *ngrxLet="myObs$ as myObs">
  <p> {{ myObs }} </p>
</ng-container>

myComponent.component.ts

@Component({
  selector: 'my-component',
  standalone: true,
  imports: [CommonModule, LetDirective],
  templateUrl: './my-component.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent implements OnInit {
  myObs$: Observable<string> = of('');
  myObsService = inject(MyObsService);
  ngOnInit() {
    this.myObs$ = this.myObsService.myObs$;
  }
}

实际运行时组件完全正常,但在Jest单元测试中,*ngrxLet指令包裹的内容始终无法渲染。我参考Angular组件测试文档后编写了测试代码:

const myObsContent = 'myObs content';

describe('myComponent tests', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [LetDirective, MyComponent],
      providers: [
        { provide: MyObsService, useValue: {myObs$: of(myObsContent)}},
      ],
    }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  })

  it('should show myObs content', async () => {
    await fixture.whenStable();
    expect(fixture.debugElement.nativeElement.textContent.includes(myObsContent))
      .toBeTruthy();
  })
})

测试结果始终显示内容不包含myObs content。我还尝试过:

  • 用fakeAsync替代async
  • 使用BehaviorSubject推送值,将冷Observable转为热Observable

但所有尝试都无效,*ngrxLet内的内容依旧无法在测试中渲染。

请问:

  1. 是否有针对Ngrx LetDirective的测试相关文档?
  2. 还有哪些可行的替代方案?

内容的提问来源于stack exchange,提问作者Natalia Cáceres

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:13:20