Testing callbacks that are not called with Jest?

為{幸葍}努か 提交于 2019-12-11 07:20:16

问题


Is there a way to test that a callback is not called with Jest?

For example:

o.subscribe(cb, cbError, cbComplete);

The cb and cbComplete callbacks should fire and the cbError callback should not fire.

is there a way to test that cbError is never called?


回答1:


Per @Richard's comment:

let error = false;
let cbError = ()=> { error =true };
let cbComplete = ()=>{
  complete = true;
  expect(complete).toBeTruthy();
  expect(error).toBeFalsy();
  done(); //This is the async callback that Jest provides to let Jest know that the test is done.

}

Inside the complete callback we test that error is still false. Since it's false after the Observable completes, the cbError callback was never called, because that callback is mutually exclusive from the other callbacks.

Side Note

This sort of gives an indication that the cbError is not called. By design the cbError and cbComplete callbacks are meant to be mutually exclusive, but we can't call done() from jest in both places, because it would equal a race condition in the test, so it that essentially we have to trust the design in this case. If anyone has any other thoughts on this please leave a comment.



来源:https://stackoverflow.com/questions/53194913/testing-callbacks-that-are-not-called-with-jest

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