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 remended 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 ments in the code above. Is this the remended way to execute a callback, which is an argument of the mocked function?
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 remended 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 ments in the code above. Is this the remended way to execute a callback, which is an argument of the mocked function?
Share Improve this question edited Jun 21, 2019 at 14:54 xavier 2,0694 gold badges23 silver badges57 bronze badges asked May 7, 2018 at 7:43 Shawn McleanShawn Mclean 57.5k96 gold badges281 silver badges412 bronze badges1 Answer
Reset to default 8Since 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.