У меня проблема с модульным тестированием некоторых функций в компоненте, где вызывается функция, которая возвращает обещание, а само обещание содержит наблюдаемую подписку.
Я издевался над наблюдаемым ответом, но я не уверен, как это работает правильно.
Вот функции компонентов, о которых идет речь:
public addAncillary(ancillaryCode: AncillaryCode): void {
this.ancillariesArray.push(ancillaryCode);
// This code is to be refactored to remove this logic call the ancillary service to calculate quote price
if (ancillaryCode === AncillaryCode.BuildingsAD || ancillaryCode === AncillaryCode.ContentsAD) {
this.getRequote(this.selectedTier)
.then((price: number) => {
this.adjustedCurrentTierPrice = (price + this.generatePriceWithAncills());
this.redrawTable();
});
} else {
let ancillary = this.selectedTier.ancillaries.find(ancillary => ancillary.code === ancillaryCode);
this.adjustedCurrentTierPrice += ancillary.price + ancillary.taxAmount;
}
this.rows = this.getRows();
}
Как видите, вышеприведенная функция содержит вызов функции, которая возвращает обещание.
public getRequote(tier): Promise<number> {
return new Promise((resolve, reject) => {
this.Modal.load('loading', true);
const quotePayload: Quote = {
...this.quoteRequest,
quoteNumber: this.quoteResponse.quoteResponse.quoteRetrieval.quoteNumber,
quoteVersion: this.quoteResponse.quoteResponse.quoteRetrieval.quoteVersion,
};
this.quoteService.getRequote(quotePayload, [...this.ancillariesArray], this.selectedTier)
.subscribe((response) => {
this.Modal.close('loading', true);
this.quoteResponseStore.change(response);
// remove this.quoteResponse to use this.quoteResponse.get()
this.quoteResponse = response;
const selectedTierQuote = response.quoteResponse.homeInsuranceQuote.home[0].tiers.find((tierIteration) => {
return tier.name === tierIteration.name;
});
resolve(selectedTierQuote.annualPremium.total);
});
});
}
И как вы можете видеть здесь, эта функция возвращает обещание, которое само разрешается после подписки на наблюдаемое.
Вот моя попытка проверить это:
fit('Should call call the Quote Service Requote method and update premium when AD is given to addAncillary method', fakeAsync(() => {
const quoteServiceMock = TestBed.get(QuoteService);
const modalServiceMock = TestBed.get('Modal');
let quoteServiceSpy, addAncillarySpy, modalLoadingSpy;
quoteServiceSpy = spyOn(quoteServiceMock, 'getRequote').and.callThrough();
addAncillarySpy = spyOn(component, "addAncillary").and.callThrough();
modalLoadingSpy = spyOn(modalServiceMock, 'load').and.callThrough();
component.addAncillary(AncillaryCode.BuildingsAD);
flush();
fixture.whenStable()
.then(() => {
expect(addAncillarySpy).toHaveBeenCalledWith(AncillaryCode.BuildingsAD);
expect(modalLoadingSpy).toHaveBeenCalled();
expect(quoteServiceSpy).toHaveBeenCalled();
expect(component.adjustedCurrentTierPrice).toEqual(132.55);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#total-premium').textContent).toEqual(' £132.55 ');
});
}));
Кто-нибудь может увидеть, что я здесь не так?Сам тест не работает, как ожидалось, по цене, которая тестируется снизу и не обновляется с поддельного сервиса.Я тоже издевался над сервисом цитирования в тесте, чтобы настоящие http-звонки не происходили.
Спасибо