单元测试 Angular 时,异步方法始终 return 为真

Async method always return true while unit testing Angular

我正在为 angular 组件之一编写单元测试用例,但单元测试未通过。 我有一种方法可以根据逻辑计算分钟数和 return true 或 false。

  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 方法始终 return 正确。我也尝试过不模拟,尝试将值传递给 createdTime,并在按预期调试方法 returns false 但是 post 我不知道发生了什么,它只是执行 if 循环而不是否则循环。

这是我的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();
  });

关于isLesserthanExpirationTime没有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 (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();
  });