【发布时间】:2019-10-10 18:45:36
【问题描述】:
我试图测试一个方法的“错误案例”,但我认为如果我模拟一个方法,这个模拟会影响我所有的其他测试。
所以我尝试将我的方法的成功案例和错误案例分成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();
});
}
);
谢谢!
【问题讨论】:
-
不确定这是否是您的问题,但您应该在测试中使用
fakeAsync -
我尝试了使用 try/catch 的异步方法,Antonis 下面的解决方案按预期工作! :) 谢谢你