微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 ngIf 异步管道可观察的茉莉花大理石测试

如何解决使用 ngIf 异步管道可观察的茉莉花大理石测试

我想用 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.

服务或 observable 本身没有问题,但在我看来,由于某种原因,DOM 不会使用将呈现组件的异步管道触发更改检测。

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

解决方法

您的订阅是异步的。这意味着您的 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(); 
}));
,

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。