首页 > 解决方案 > Angular:订阅中的单元测试变量

问题描述

我有一个在订阅中设置几个值的函数:

private getAllStatuses(): void {
   this.refControllerService.getAllStatus().subscribe(data => {
      this.StatusDTOList = data;
      this.canEditDate = this.isEditableStatus();
      this.isDEDUser = this.userAuthorisationService.isDEDUser();
      this.initialised = true;
   });
}

canEditDate&isDEDUser都是私有的,它们可以在另一个函数中访问:

public canEdit(): boolean {
   return this.isDEDUser && this.canEditDate;
}

我试图在我的测试中设置这两个值,但到目前为止还没有任何外观:

it('StatusComponent canEdit should return false', () => {
    spyOn(refControllerService, 'getAllStatus').and.returnValue(of({ canEditDate: false, isDEDUser: false }) as any)
    spyOn(userAuthorisationServiceSpy, 'isDEDUser').and.returnValue(false)
    component.ngOnInit();
    expect(component.canEdit).toBeFalsy();
});

我尝试了几种不同的方法,并且搜索了类似的问题,我对角度比较陌生,有人可以解释一下我正在尝试什么吗?我可以在测试中设置该订阅中的值,以便我可以打开和关闭这些值canEdit()吗?

标签: angularunit-testingkarma-jasminesubscribe

解决方案


这个问题有很多不清楚的地方。我会勇敢地尝试回答它。

考虑到CanEdit is public and is the function under test我们需要执行函数来测试它的结果。更改expect(component.canEdit)expect(component.canEdit()).

我们看不到如何getAllStatuses执行。我会使用它在ngOnInit. 该函数使用对 Observable 的订阅以异步方式执行一些操作。这意味着我们需要等待执行。通常(并非总是如此)await fixture.whenStable()足以等待异步内容的执行。我想这个测试将存档所需的结果:

it('StatusComponent canEdit should return false', async () => {
    spyOn(refControllerService, 'getAllStatus').and.returnValue(of({ canEditDate: false, isDEDUser: false }) as any)
    spyOn(userAuthorisationServiceSpy, 'isDEDUser').and.returnValue(false)

    component.ngOnInit();
    await fixture.whenStable();

    expect(component.canEdit()).toBeFalsy();
});

推荐阅读