chore(backend-common): Fixing the headers sent issue so we dont send the response twice

This commit is contained in:
blam
2020-06-24 11:18:58 +02:00
parent 18a6a68dd0
commit f42a541ade
2 changed files with 26 additions and 0 deletions
@@ -34,6 +34,29 @@ describe('errorHandler', () => {
expect(response.text).toBe('some message');
});
it('doesnt try to send the response again if its already been sent', async () => {
const app = express();
const mockSend = jest.fn();
app.use('/works_with_async_fail', (_, res) => {
res.status(200).send('hello');
// mutate the response object to test the middlware.
// it's hard to catch errors inside middleware from the outside.
// @ts-ignore
res.send = mockSend;
throw new Error('some message');
});
app.use(errorHandler());
const response = await request(app).get('/works_with_async_fail');
expect(response.status).toBe(200);
expect(response.text).toBe('hello');
expect(mockSend).not.toHaveBeenCalled();
});
it('takes code from http-errors library errors', async () => {
const app = express();
app.use('/breaks', () => {
@@ -53,7 +53,10 @@ export function errorHandler(
next: NextFunction,
) => {
if (response.headersSent) {
// If the headers have already been sent, do not send the response again
// as this will throw an error in the backend.
next(error);
return;
}
const status = getStatusCode(error);