Angular/RxJS 6 - 如何对 next() 触发的指令引发异常进行单元测试

M's*_*ph' 5 unit-testing throw jasmine rxjs angular

在迁移到 RxJs6 之前,我的单元测试之一是:

it('should do what I expect, () => {
  expect(() => {
    myComponent.mySubject.next({message: 'invalid'});
  }).toThrow('invalid is not an accepted message');
})
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我订阅了主题并调用了一个可以抛出异常的私有方法。看起来像这样的东西:

export class MyComponent {
  //...
  mySubject = new Subject();
  //...
  ngOnInit(){
    this.mySubject.subscribe(obj => this._doSomething(obj))
  }
  //...
  private _doSomething(obj) {
    if ('invalid' === obj.message) {
      throw new Error('invalid is not an accepted message');
    }
    //...
  }
}
Run Code Online (Sandbox Code Playgroud)

自从我迁移到 RxJs6 以来,这个 UT 不再工作(以前工作过),我不知道如何使它工作。

我阅读了迁移指南,尤其是本节:替换同步错误处理,但它是关于subscribe(),而不是next()......

提前致谢

M's*_*ph' 1

我找到了一个解决方法。

不确定相关性,但它似乎对我有用。

我使用角度测试方法fakeAsynctick触发未处理异常的发射。

转换 :

it('should do what I expect, () => {
  expect(() => {
    myComponent.mySubject.next({message: 'invalid'});
  }).toThrow('invalid is not an accepted message');
})
Run Code Online (Sandbox Code Playgroud)

进入 :

it('should do what I expect, fakeAsync(() => {
  myComponent.mySubject.next({message: 'invalid'});
  expect(() => tick())
    .toThrow('invalid is not an accepted message');
}))
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这个技巧还让我确信,如果不抛出异常,测试就会失败。