问题
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