[异步方法在单元测试Angular时始终返回true

问题描述 投票:0回答:1

我正在为某个角度组件编写单元测试用例,但没有通过单元测试。我有一种计算分钟数并根据逻辑返回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方法始终返回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();
  });
angular unit-testing async-await karma-jasmine angular8
1个回答
0
投票

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();
  });
© www.soinside.com 2019 - 2024. All rights reserved.