【问题标题】:Jasmine .and.throwError() is not caught by .catch in original codeJasmine .and.throwError() 在原始代码中未被 .catch 捕获
【发布时间】:2018-08-16 18:38:18
【问题描述】:

我正在为一个函数编写一个测试,并且必须触发该函数的 .catch 部分,但 Jasmine 的间谍由于某种原因不能这样做。 待测方法:

foo(){
doStuff()
.catch((error) => {
    //stuff I still have to test
    bar()
})

}

doStuff() 返回一个 Promise(因此是 .catch-Setup),但对于这个测试,它应该会抛出一个错误。

这是我的测试:

it('tests the error handling of foo',(done) =>{
spyOn(object,'foo').and.throwError('Test Error');

object.foo();

expect(object.bar).toHaveBeenCalled();
done();

});

我处理这个问题的方式是错误的吗?这是茉莉花的错误吗? (谷歌没有找到任何东西) [我坚持(完成)设置,因为几乎所有其他测试都是异步的,我想保持这种风格]

[我无法更改要测试的代码]

【问题讨论】:

    标签: javascript testing jasmine throw


    【解决方案1】:

    如果你调用and.throwError(...);,你会在测试方法中抛出错误。

    您可以尝试返回 Promise 拒绝:

    spyOn(object, 'foo').and.rejectWith(new Error('Test Error'));

    【讨论】:

      【解决方案2】:

      我想我遇到了和你类似的问题。以下是我的解决方法

      import { throwError } from 'rxjs';
      
      it(`...`, fakeAsync(() => {
          spy = spyOn(authService, 'signIn').and.returnValue(throwError(loginError));
          /* do things */
          expectSnackbar('error', loginError);
          expect(authService.ensureLogin).toHaveBeenCalled(); 
      }));
      

      下面是对 signIn 方法的调用:

      return this.authService
          .signIn(payload.email, payload.password)
          .map((userId: string) => {
              // Whatever
          })
          .catch(error => {
              // Do something with the error
          });
      

      以及在signIn中抛出的错误是什么样子的

      public signIn(email: string, password: string): Observable<string> {
          return this.jsonServerService.get('login').pipe(
              map(users => {
                  if (/* valid */) {
                      return user.userId;
                  } else {
                      throw new Error('Error');
                  }
              }),
          );
      }
      

      【讨论】:

      • 什么是V。这是哪里来的?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多