【问题标题】:Angular: unit test varibles in subscribeAngular:订阅中的单元测试变量
【发布时间】:2021-07-15 12:42:11
【问题描述】:

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

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();
});

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

【问题讨论】:

  • 你什么时候打电话给canEdit?是this.isEditableStatus()吗?
  • CanEdit 是公开的,是被测函数,可以随时调用...
  • this.isEditableStatus() 在做什么?你确定它没有抛出任何错误,因为它没有被嘲笑?

标签: angular unit-testing karma-jasmine subscribe


【解决方案1】:

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

考虑到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();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2021-06-28
    • 2018-10-03
    • 2020-09-23
    • 1970-01-01
    • 2018-02-01
    • 2017-11-23
    相关资源
    最近更新 更多