【问题标题】:Jasmine marble testing observable with ngIf async pipe使用 ngIf 异步管道可观察到 Jasmine 大理石测试
【发布时间】:2023-03-16 22:00:02
【问题描述】:

我想用 jasmine-marble 测试来测试 Observable,但不幸的是我不知道如何触发 ngIf 的更改检测,这应该呈现组件。

这是我的课程的简化版本:

export class MyComponent implements OnInit {
  data$: Observable<{data: any[]}>;

  constructor(private baseService: BaseService) { }

  ngOnInit(): void {
    this.data$ = this.baseService.get(endpoint);
  }
}

还有我的html文件:

<custom-component *ngIf="data$ | async as value" [data]="value.data">
    ...
</custom-component>

这是我当前的测试,失败了:

it ('should display custom component', fakeAsync(() => {
    const expected = cold('a|',  {a: {data: [{id: 1}]}});
    baseServiceStub.get.and.returnValue(expected);
    component.ngOnInit();
    fixture.detectChanges();
    tick();
    expect(component.data$).toBeObservable(expected); // this passes and the observable also holds the correct value
    expect(baseService.get).toHaveBeenCalledWith(endpoint); // this passes aswell
    component.data$.subscribe(val => {
      console.log(val); // here I can log the correct value of the observable ( {data: [{id:1}]})
    });
    expect(fixture.debugElement.query(By.css('custom-component'))).not.toBeNull(); // this fails
}));

不幸的是我得到的都是这个

Error: Expected null not to be null.

服务或可观察对象本身没有问题,但在我看来,由于某种原因,DOM 不会触发使用异步管道来渲染组件的更改检测。

PS:当我使用getTestScheduler().flush() 时,我得到了错误Can't subscribe to undefined

【问题讨论】:

  • 请添加一个 stackblitz 示例,您说服务和 observable 都没有问题。但是,我不相信你的话:)
  • 不应该吗? baseServiceStub.get.and.returnValue(of({data: [{id: 1}]})); 来自 rxjs?
  • 这是我当前的 StackBlitz stackblitz.com/edit/jasmine-in-angular-phifhp?file=src/app/… 。出于某种原因,由于格式问题,StackOverflow 不允许我编辑我的帖子...

标签: angular angular-test jasmine-marbles


【解决方案1】:

您的订阅是异步的。这意味着您的console.log 可以在您最后一个expect 之后触发。在您最后的预期中,数据可能尚未加载,因此该值未定义。

使用tick(100) 代替tick() 可能会起作用。请注意,这会使您的测试慢 100 毫秒。

你也可以切换到 async 并等待 observable 返回一个值:

it ('should display custom component', async(() => {
    ...
    // tick(); //dont call this
    ...
    await component.data$.pipe(take(1)).toPromise()
    expect(fixture.debugElement.query(By.css('custom-component'))).not.toBeNull(); 
}));

【讨论】:

  • 我并没有完全得到我想看到的结果,即使我理解你想要达到的目标。您能否偶然编辑我的 StackBlitz。 stackblitz.com/edit/…
【解决方案2】:

我通过创建另一个测试套件解决了这个问题,我在其中手动定义了 observable 的值。我对这种方法并不完全满意,但它可以解决我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 2020-07-27
    • 2020-05-21
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多