如何在Jasmine / Angular2 / Typescript中异步抛出异常? [英] How to expect an asynchronously thrown exception in Jasmine / Angular2 / Typescript?

查看:449
本文介绍了如何在Jasmine / Angular2 / Typescript中异步抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个Angular2 / Typescript方法,返回 nothing 并实现可能抛出的.subscribe()处理程序,例如:

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 => {},
  );
}

(暂时假设这个.subscribe有一个很好的理由()处理程序(可能有条件地)拒绝没有其他可测试的副作用,因此只导致错误消息冒泡到应用程序的顶部。)

(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:

如何处理与Jasmine异步代码中抛出的错误?

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

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

推荐答案

我通过stubbing console.error()方法(在这种情况下,我使用Sinon)解决了这个问题:

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?

这篇关于如何在Jasmine / Angular2 / Typescript中异步抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆