I am testing an express API with jest and supertest. The goal is to test a post request with form parameters.
My test code is something like this:
test('create (name=John)', async () => {
const res = await request(app)
.post('/create')
.type('form')
.set('Authorization', 'secret')
.send('name=John');
expect(res.statusCode).toBe(400);
expect(res.body).toMatchObject({
"status": "error",
"message": "Type is empty"
});
})
The route is similar to this:
router.post(
'/create',
oauth.authenticate(),
async function (req: express.Request, res: express.Response) {
if (!req.body || !req.body.name) {
return Base.badResponse(res, 400, 'Name is empty');
}
if (!req.body.type) {
return Base.badResponse(res, 400, 'Type is empty');
}
// Logic here
}
);
Im also using bodyParser to get the body formatted.
Testing with Postman is successful, so there is no general problem.
The request header for content-length have a value of 9 which represents the length of the parameter sent. The content-type is 'application/x-www-form-urlencoded' and correct.
My question is, why is request body still undefined wenn running the code with supertest?