Skip to content

Instantly share code, notes, and snippets.

@mattiaerre
Last active June 13, 2021 10:33
Show Gist options
  • Save mattiaerre/4cdc922be4ba56f831f88aafb4c760c9 to your computer and use it in GitHub Desktop.
Save mattiaerre/4cdc922be4ba56f831f88aafb4c760c9 to your computer and use it in GitHub Desktop.
req, res and chaining

How to test it in an Express app

app.get('/playground', handler);

200

http://localhost:9000/playground

Request URL: http://localhost:9000/playground
Request Method: GET
Status Code: 200 OK
{"message":"OK"}

500

http://localhost:9000/playground?error=KO

Request URL: http://localhost:9000/playground?error=KO
Request Method: GET
Status Code: 500 Internal Server Error
{"message":"KO"}
async function handler({ query: { error } }, res) {
if (error) {
return res.status(500).send({ message: error });
}
return res.status(200).send({ message: 'OK' });
}
module.exports = handler;
const handler = require('./handler');
describe('handler', () => {
const scenarios = [
{
description: 'w/o error',
error: null,
status: 200
},
{
description: 'w/ error',
error: 'Oh Noes!',
status: 500
}
];
scenarios.forEach(({ description, error, status }) => {
it(description, async () => {
const req = { query: { error } };
const res = {
send: jest.fn(),
status: jest.fn(() => res)
};
await handler(req, res);
expect(res.status).toBeCalledWith(status);
expect(res.send.mock.calls[0][0]).toMatchSnapshot();
});
});
});
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`handler w/ error 1`] = `
Object {
"message": "Oh Noes!",
}
`;
exports[`handler w/o error 1`] = `
Object {
"message": "OK",
}
`;
@tecnocriollo
Copy link

Very nice example. It saves me a lot of time

@subrato-pattanaik
Copy link

Yes, this is a very good example. One question if we don't pass the status mock function to your mock response then what will happen?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment