如何在笑话角中嘲笑一个承诺?



方法如下:

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();
}

我的测试包含捕获错误:

service.signMessage('xml', 'mbo').catch((errCode) => {
expect(errCode).toBe('empty');
done();
});
});

我需要添加什么逻辑来覆盖if语句?我一定要嘲笑承诺吗?不知道要做什么。我试过了:

it('signMessage', async (done) => {
const spy = spyOn(service, 'pingDigitalSignatureApp').and.returnValue(
new Promise((resolve) => resolve('someVal')),
);
service.pingDigitalSignatureApp();
expect(spy).toHaveBeenCalled();
done();
});

什么也没发生,从某种意义上说,test没有转到if语句。建议感激。

由于您正在对所讨论的方法进行.toPromise(),因此您需要返回Observable而不是承诺。是的,您需要返回一个满足if条件的对象。

试试这个:

// 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');
});

最新更新