【问题标题】:Angular 6 Unit Testing Dependant PromisesAngular 6 单元测试依赖承诺
【发布时间】:2018-11-19 13:49:55
【问题描述】:

我是 Angular 新手,目前正在为我的应用程序编写单元测试。我真的很困惑,似乎无法为我当前的任务编写单元测试。 我的组件使用以下方法:

async updateLevelModes(level: Level) {
    const updateModes: Promise<any>[] = [];
    for(let mode of level.Modes) {
      const updateMode = this.modeService.updateMode(mode);
      updateModes.push(updateMode);
    }
    await Promise.all(updateModes);
    const update = await this.LevelService.updateLevel(level);
    level.Id = update._id;
  }

它使用两个服务,modeService 和 levelService。

我的 LevelService.ts 看起来像这样

async updateLevel(level: Level): Promise<void> {
    const formdata = new FormData();
    formdata.append('Name', level.Name);
    formdata.append('Description', level.Description);
    formdata.append('ImageFile', level.ImageFile);

    const resultLevel = await this.http.put<IStep>(this.postStepsUrl+'/'+step.Id, formdata)
      .pipe(catchError(this.errorHandler))
      .toPromise<IStep>();
    this.HandleStepResult(Level, resultLevel);
  }

我应该如何为如此复杂的方法编写测试?请帮忙

【问题讨论】:

  • updateLevelModes 的测试中,您可以模拟modeService.updateModeLevelService.updateLevel,以便它们返回已解决的承诺,因此您不必处理服务中的所有逻辑。然后您可以断言level.Id 已正确更新。

标签: angular typescript http testing jasmine


【解决方案1】:

并不是一个“复杂”的方法:

  • 对于每种模式,更新它
  • 更新关卡

从提供的代码中,你需要两个模拟和一个期望:

it('should update the level ID', () => {
  const newID = 5;
  spyOn(component['modeService'], 'updateMode').and.returnValue(Promise.resolve(true));
  spyOn(component['modeService'], 'updateLevel').and.returnValue(Promise.resolve({ id: newID }));

  component.updateLevelModes(component.level);

  expect(component.level.id).toEqual(newID);
});

因为你单元测试你的组件,你应该模拟你的依赖。如果您不这样做,那么您的测试将非常随机且难以实施。

这意味着如果你模拟你的服务,你不必知道它做了什么,你只需要知道它返回一个带有 ID 的新关卡。

在业务方面,这项测试是您防止副作用所需的全部。

【讨论】:

  • 感谢您的回复以及代码。我仍然无法将它带到工作中。在倒数第二行,我无权访问 level 属性。
  • component['level'] 应该绕过它
  • 好吧,无论你的关卡来自哪里!我虽然它是你的组件的成员,对不起
猜你喜欢
  • 2016-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多