Given an Angular2/Typescript method that returns nothing and implements a .subscribe() handler which might throw, such as this:
onSubmit() { // returns nothing
this.service.someCall(this.someData).subscribe(
data => {
return Promise.reject('This is an asynchronously thrown error.');
},
err => {},
);
}
(For the moment, let's assume that there's a good reason for this .subscribe() handler to (probably conditionally) reject without other testable side-effects, thus resulting only in an error message bubbling up to the top of the application.)
How would one go about testing that this method resulted in a rejected Promise?
I found some people with the same question, but no elegant answers:
How to deal with thrown errors in async code with Jasmine?
I solved this problem by stubbing the console.error() method (in this case, I am using Sinon):
it('should throw exception from component on submit', (done) => {
// Jasmine isn't capable of capturing an exception thrown from an *asynchronous* operation.
// However, that error eventually finds its way to console.error(), so we can stub
// that method and wait for it to be called.
sandbox.stub(console, 'error').callsFake((...err) => {
expect(err[1]).toEqual('This is an asynchronously thrown error.');
done();
});
component.onSubmit();
});
Are there any other/better ways to go about this?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.