Angular 9 + jest: юнит-тест, макет обещания и метод проверки, вызываемый затем - PullRequest
0 голосов
/ 16 марта 2020

Мне нужна помощь, я не знаю, как смоделировать обещание и проверить, вызывается ли метод after в функции then ().

Мой код выглядит следующим образом, когда я нажимаю на кнопку сохранения в моей форме:

// File : myComponent.ts
save() {
   const myObject = new MyObject({field: this.form.value.field});

   this.myService.saveObject(myObject).then(() => { // I'd like to mock this
     this.closeDialog(true);
  }, error => {
     this.otherFunction(error);
  });
}


// File : myService.ts
saveOject(myObject: MyObject): Promise<any> {
  return this.myApi.save(myOject).toPromise().then(res => res);
}


// File : myApi.ts
save(myObject: MyObject) {
  return this.http.post('url, myObject);
}

Я пытаюсь протестировать эту функцию, и я хотел бы посмеяться (или заглушка? Я не знаю разницы) функция saveObject, когда обещание разрешается, а дело в том, что это не так.

Мой тестовый файл на актуэле выглядит так:

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let myService: MyService;

  beforeEach(async (() => {
     TestBed.configureTestingModule(
   ).compileComponents();

   myService = TestBed.inject(MyService);
  }

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    spyOn(myService, 'saveOject').and.returnValue(new Promise(resolve => resolve()));
  });

  it('should call closeDialog method when save form is successful', () => {
     const spyCloseDialog = jest.spyOn(component, 'closeDialog');

     component.save();
     fixture.detectChanges(); // It's a test, I don't know if it's useful
     expect(spyCloseDialog).toHaveBeenCalledTimes(1); // It's 0 because I don't know how to be in the then part of my function
  });

}

Кто-нибудь может мне помочь? С уважением

1 Ответ

2 голосов
/ 17 марта 2020

Есть два варианта на выбор:
1) использовать fakeAsyn c, например:

it('should call closeDialog method when save form is successful', fakeAsync(() => {
     const spyCloseDialog = jest.spyOn(component, 'closeDialog');

     component.save();
     tick(50);
     expect(spyCloseDialog).toHaveBeenCalledTimes(1);
}));

2) положить expect внутрь then, например

component.save().then(() => expect(spyCloseDialog).toHaveBeenCalledTimes(1)); 

В вашем тесте вы должны импортировать HttpClientTestingModule, чтобы тест выполнялся успешно, и не выдается ошибка, когда angular пытается запустить вызов http.

...