简体   繁体   中英

Testing callbacks that are not called with Jest?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM