Skip to content

Commit b3c6bb1

Browse files
committed
test: verify route-level middleware req.body modifications reach handler
1 parent 4b40459 commit b3c6bb1

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

packages/express-wrapper/test/server.test.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,3 +276,59 @@ test('should return a 400 when request fails to decode', async () => {
276276

277277
assert(response.body.error.startsWith('Invalid value undefined supplied to'));
278278
});
279+
280+
test('middleware that modifies req.body should reach handler even without routeHandler()', async () => {
281+
const PostWithData = httpRoute({
282+
path: '/data',
283+
method: 'POST',
284+
request: httpRequest({
285+
body: {
286+
originalField: t.string,
287+
addedByMiddleware: optional(t.string),
288+
},
289+
}),
290+
response: {
291+
200: t.type({
292+
originalField: t.string,
293+
addedByMiddleware: optional(t.string),
294+
}),
295+
},
296+
});
297+
298+
const testApiSpec = apiSpec({
299+
'test.route': {
300+
post: PostWithData,
301+
},
302+
});
303+
304+
const modifyBodyMiddleware: express.RequestHandler = (req, _res, next) => {
305+
req.body.addedByMiddleware = 'ADDED';
306+
next();
307+
};
308+
309+
const handler = async (params: { originalField: string; addedByMiddleware?: string }) => {
310+
return {
311+
type: 200,
312+
payload: {
313+
originalField: params.originalField,
314+
addedByMiddleware: params.addedByMiddleware,
315+
},
316+
} as const;
317+
};
318+
319+
const app = createServer(testApiSpec, (app: express.Application) => {
320+
app.use(express.json());
321+
return {
322+
'test.route': {
323+
post: { middleware: [modifyBodyMiddleware], handler },
324+
},
325+
};
326+
});
327+
328+
const response = await supertest(app)
329+
.post('/data')
330+
.send({ originalField: 'test' })
331+
.expect(200);
332+
333+
assert.equal(response.body.addedByMiddleware, 'ADDED', 'addedByMiddleware should be present because req.body is part of req.decoded');
334+
});

0 commit comments

Comments
 (0)