[英]How to mock a promise in jest angular?
Here is the method I have:这是我的方法:
async signMessage(xml, mbo): Promise<any> {
try {
const isSignatureAppAlive = await this.pingDigitalSignatureApp().toPromise();
if (isSignatureAppAlive.alive) {
try {
this.signedMsg = await this.getSignedMsg(xml, mbo).toPromise();
return this.signedMsg;
} catch (er) {
return this.handleSignatureAppErrorCodes(er.error.errorCode);
}
}
} catch (e) {
this.showSignatureInfoModal();
return this.handleError({ message: 'empty' });
}
}
getSignedMsg(msg, mbo): Observable<any> {
this.signDocument.title = '';
this.signDocument.content = btoa(msg);
this.signDocument.contentType = 'application/xml';
this.signDocument.uriOrIdToSign = '';
this.postParam.certificateAlias = mbo;
this.postParam.digestAlgorithm = 'SHA1';
this.postParam.documents = [];
this.postParam.documents.push(this.signDocument);
this.postParam.signingMethod = 'xmldsig';
this.postParam.envelopingMethod = 'enveloped';
return this.http.post<any>(SERVICE_URL + 'sign', this.postParam, httpOptions).pipe();
}
My test covers catching error:我的测试涵盖了捕获错误:
service.signMessage('xml', 'mbo').catch((errCode) => {
expect(errCode).toBe('empty');
done();
});
});
What logic do I need to add in order to cover if statement?为了涵盖 if 语句,我需要添加什么逻辑? Do I have to mock a Promise?
我必须模拟 Promise 吗? Not sure what to do here.
不知道在这里做什么。 I tried this:
我试过这个:
it('signMessage', async (done) => {
const spy = spyOn(service, 'pingDigitalSignatureApp').and.returnValue(
new Promise((resolve) => resolve('someVal')),
);
service.pingDigitalSignatureApp();
expect(spy).toHaveBeenCalled();
done();
});
Nothing happens, in a sense that test doesn't go to if statement.什么都没有发生,从某种意义上说,测试不会进入 if 语句。 Advice appreciated.
建议表示赞赏。
Since you're doing a .toPromise()
on the method in question, you need to return an Observable
and not a promise.由于您正在对相关方法执行
.toPromise()
,因此您需要返回Observable
而不是 Promise。 And yes, you need to return an object where the if
condition will be satisfied.是的,您需要返回一个满足
if
条件的对象。
Try this:尝试这个:
// we don't need done
it('signMessage', async () => {
// return an observable
const spy = spyOn(service, 'pingDigitalSignatureApp').and.returnValue(
of({ alive: true } as any)
);
// make getSignedMsg return hello
spyOn(service, 'getSignedMsg').and.returnValue(of('hello'));
// await for the result
const result = await service.pingDigitalSignatureApp();
expect(spy).toHaveBeenCalled();
// expect it to go inside of the if and it returned hello
expect(result).toBe('hello');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.