【问题标题】:Async method always return true while unit testing Angular在单元测试 Angular 时,异步方法总是返回 true
【发布时间】:2020-03-30 17:51:38
【问题描述】:

我正在为其中一个角度组件编写单元测试用例,但没有通过单元测试。 我有一种方法可以计算分钟并根据逻辑返回真或假。

  async isLesserthanExpirationTime(creationTime: string) {
    var currentTime = new Date(new Date().toISOString());
    var minutes = (new Date(currentTime).valueOf() - new Date(creationTime).valueOf()) / 60000;
    if (minutes > 20)
      return false;

return true;

}

这是另一种方法,取决于根据上述方法进行决策的方法。

async getDetailsForId(id: string) {
    if (await this.isLesserthanExpirationTime(createdTime))
      let response = await this.DLService.getById(id).toPromise();
      //something
    else
      let response = await this.VDLService.getById(id).toPromise();
      //something
      }

我无法为此获得正确的 UT,islesserthanexpirationtime 方法总是返回 true。我也尝试过不进行模拟,尝试将值传递给 createdTime,并且在调试该方法时按预期返回 false,但发布我不知道发生了什么,它只是执行 if 循环而不是 else 循环。

这是我的 UT

it('should has ids', async() => {
    spyOn(VDLService, 'getById');
    spyOn(component, 'isLesserthanExpirationTime').and.returnValue(false);
    component.getDetailsForId(Id);
    expect(component.isLesserthanExpirationTime).toBeFalsy();
    expect(VDLService.getById).toHaveBeenCalled();
  });

【问题讨论】:

  • 你试过spyOn(component, 'isLesserthanExpirationTime').and.returnValue(Promise.resolve(false));吗?

标签: angular unit-testing async-await karma-jasmine angular8


【解决方案1】:

async没有关于isLesserthanExpirationTime的内容,改成:

 isLesserthanExpirationTime(creationTime: string) {
    var currentTime = new Date(new Date().toISOString());
    var minutes = (new Date(currentTime).valueOf() - new Date(creationTime).valueOf()) / 60000;
    if (minutes > 20)
      return false;

  return true;
}

将函数改为:

async getDetailsForId(id: string) {
    if (this.isLesserthanExpirationTime(createdTime))
      let response = await this.DLService.getById(id).toPromise();
      //something
    else
      let response = await this.VDLService.getById(id).toPromise();
      //something
      }

还有单元测试:

it('should has ids', async(done) => { // add done here so we can call it when it is done
    spyOn(VDLService, 'getById').and.returnValue(Promise.resolve('hello world')); // up to you what you want to resolve it to
    spyOn(component, 'isLesserthanExpirationTime').and.returnValue(false);
    await component.getDetailsForId(1); // make sure this promise resolves
    expect(component.isLesserthanExpirationTime).toBeFalsy();
    expect(VDLService.getById).toHaveBeenCalledWith(1);
    done();
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 2019-05-30
    • 2020-07-14
    • 1970-01-01
    • 2021-10-13
    • 2012-12-09
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多