Метод Asyn c всегда возвращает true, пока тестируется модуль Angular - PullRequest
0 голосов
/ 30 марта 2020

Я пишу тестовый блок для одного из компонентов angular, но я не проходил модульный тест. У меня есть метод, который вычисляет минуты и возвращает истину или ложь на основе логики c.

  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. Я также пытался без насмешек, пытался передать значение в selectedTime, и во время отладки метод возвращает false, как и ожидалось, но сообщая, что я не знаю, что происходит, он просто выполняет if l oop вместо l oop.

Вот мой 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();
  });

1 Ответ

0 голосов
/ 31 марта 2020

Там нет ничего 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();
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...