Express, req, res, and chaining
Given that Express is my favorite Node.js web application framework, very often I find myself having to unit test handler functions. Normally these functions are simply returning the send
or the render
methods invocation on the res
object. Sometimes a status
method is invoked right before the ones mentioned above, to explicitly set the HTTP status code (e.g.: res.status(500).send({ message: ‘Oh Noes!’ });
). To be able to test this I’m using the following jest mock:
const res = { send: jest.fn(), status: jest.fn(() => res)};
The above enables me to use the req
mock and be able to assert against send
whether or not status
has been invoked before.
I’ve also put together a GitHub Gist that hopefully explains this technique better.
Thanks so much to Scott Lepich for the original idea and to Nick Balestra for inspiring a more compact version of the mock.