How to expect an asynchronously thrown exception in Jasmine / Angular2 / Typescript?

三世轮回 提交于 2020-01-05 04:04:45

问题


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?

https://github.com/jasmine/jasmine/issues/529

https://gist.github.com/badsyntax/7769526


回答1:


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?



来源:https://stackoverflow.com/questions/46006944/how-to-expect-an-asynchronously-thrown-exception-in-jasmine-angular2-typescr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!