如何测试在.finally()中执行的代码

时间:2017-11-23 13:05:23

标签: rxjs

finally的工作方式与here相同。

如何测试最终运行的代码?

// code
function doCall(body) {
  isWaitingForRequestToComplete();
  return this.apiService
    .someRequest(body)
    .map(response => transform(response))
    .catch(error => Observable.of('Request failed: ' + error.message))
    .finally(() => {
      requestHasCompleted()
      console.log("Finally");
    });
}

// unit test
it('test observable', () => {
  const testBody = {};
  doCall(testBody).subscribe(() => {
    expect(isWaitingForRequestToComplete).toHaveBeenCalled();
    expect(apiService.someRequest).toHaveBeenCalled();
    console.log("Finally should have been executed");
    expect(requestHasCompleted).toHaveBeenCalled();
  });
});

输出是:

# Finally should have been executed
# Finally
# expect spy requestHasCompleted to have been called

所以在执行subscribe(next)之后调用finally,这是有道理的。将期望完成:subscribe(next, error, completed),也无济于事。

2 个答案:

答案 0 :(得分:1)

哈哈,自动完成给了我答案。 一时兴起,我只是在.之后放置一个subscribe()来查看订阅后是否有任何处理程序,并得到以下建议:.add, .closed, .remove, .unsubscribe

.add(function) Adds a tear down to be called during the unsubscribe() of this subscription

this question为例。

/// code
  source
    .finally(() => console.log('Finally callback'))
    .subscribe(value => console.log('#1 Next:', value), error => console.log('#1 Error:', error), () => console.log('#1 Complete'))
    .add(() => {
      console.log('Executed after finally is called');
    });

/// output
# ...
# Finally calllback
# Executed after finally is called

虽然我不太明白触发unsubscribe()http://reactivex.io/rxjs/class/es6/Subscription.js~Subscription.html)的原因。 我一直认为订阅只是存在,直到明确取消订阅......

答案 1 :(得分:1)

由于您使用it(...)进行测试,我认为您正在使用jasminemocha,您可以使用可选参数done来测试异步函数。< / p>

it('test observable', done => {
  this.apiService
    .someRequest(...)
    .map(...)
    .finally(done)
    .subscribe();
})

注意我使用.finally(done)告诉测试环境此方法何时正确结束。如果我没有调用done(),测试会在超时时失败。