I need to execute an argument that is a callback of a jest mock.
In the jest documentation, their callback example is about testing the first callback. I have behaviors inside nested callbacks I need to test. In the examples of promises, they use resolves
and rejects
. Is there anything like this for nested callbacks? I'm currently executing the mocked call argument, which I'm not sure if it is the recommended way.
System under test:
function execute() {
globals.request.post({}, (err, body) => {
// other testable behaviors here.
globals.doSomething(body);
// more testable behaviors here. that may include more calls to request.post()
});
}
The test:
globals.request.post = jest.fn();
globals.doSomething = jest.fn();
execute();
// Is this the right way to execute the argument?
globals.request.post.mock.calls[0][1](null, bodyToAssertAgainst);
expect(globals.doSomething.mock.calls[0][1]).toBe(bodyToAssertAgainst);
My question is in the comments in the code above. Is this the recommended way to execute a callback, which is an argument of the mocked function?
Since you don't care about the implementation of your globals.request.post
method you need to extend your mock a bit in order for your test to work.
const bodyToAssertAgainst = {};
globals.request.post = jest.fn().mockImplementation((obj, cb) => {
cb(null, bodyToAssertAgainst);
});
Then you can go onto expect that doSomething
was called with bodyToAssertAgainst
. Also, this way you can easily test if your post
would throw an Error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With