Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute mocked jest callback argument

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?

like image 369
Shawn Mclean Avatar asked Oct 15 '25 09:10

Shawn Mclean


1 Answers

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.

like image 195
Henrik Andersson Avatar answered Oct 16 '25 23:10

Henrik Andersson