我试图测试方法的“错误情况”,但我认为,如果我模拟一个方法,则该模拟会影响所有其他测试。
因此,我尝试将方法的成功案例和错误案例分成2个描述。
当我启动测试范围时,错误的情况就被涵盖了,但是控制台中的测试失败了。
https://image.noelshack.com/fichiers/2019/21/5/1558683399-test1.png
控制台信息:
https://image.noelshack.com/fichiers/2019/21/5/1558683502-test2.png
这是方法:
getAgreementSelector() {
this.isLoading = true;
this.frameworkAgreements$ = this.entityManager.getEntity(AgreementSelectorEntity, {})
.pipe(
take(1),
map((dataEntity: any) => dataEntity.value),
filter((data: Array<IFrameworkAgreement>) => !!data && data.length > 0));
this.frameworkAgreements$.subscribe((data: Array<IFrameworkAgreement>) => {
this.isLoading = false;
this.agreementValue = data;
this.error = false;
const sessionStorageFAId = sessionStorage.getItem('selectedAgreementId');
if (sessionStorageFAId) {
this.onCustomerSelected(sessionStorageFAId);
} else {
this.onCustomerSelected(this.agreementValue[0].id.toString());
}
for (let j = 0; j < this.agreementValue.length; j++) {
if (this.agreementValue[j].id.toString() === sessionStorageFAId) {
this.selectedFrameworkAgreement = this.agreementValue[j].id.toString();
}
}
}, (error: any) => {
this.isLoading = false;
if (error.status === 404 || error.status === 500 || error.status === 403) {
this.hideErrorFlag = true;
this.error = true;
}
});
}
测试:
it('should set error variables if there is an error (status 404)', () => {
// arrange
UtilsTest.mockReturnValue(component['entityManager'], 'getEntity', throwError({ status: 404 }));
// act
component.getAgreements();
component.agreements$.subscribe(() => {
// assert
expect(component.isLoadingDetails).toBeFalsy();
expect(component.hideErrorFlag).toBeTruthy();
expect(component.errorDetails).toBeTruthy();
});
}
);
谢谢!
答案 0 :(得分:0)
尝试一下:
it('should set error variables if there is an error (status 404)', async(() => {
spyOn(component['entityManager'], 'getEntity').and.throwError({ status: 404 });
try {
await component.getAgreements();
} catch (e) {
expect(component.isLoadingDetails).toBeFalsy();
expect(component.hideErrorFlag).toBeTruthy();
expect(component.errorDetails).toBeTruthy();
}
}));