i'm trying to use supertest to test some express routes, however the test throws a timeout error when i try to send post requests despite the get requests actually working.
this is the route i'm testing
router.post('/', async (req, res) => {
try {
const { command, text } = req.body;
switch (command) {
case 'abc': return;
default:
console.log('123');
}
} catch (error) {
console.error(error);
}
});
this is the test
describe('test', () => {
const app: express.Express = express();
app.use('/', route);
app.use(express.urlencoded({ extended: true }));
it('test', async () => {
await request(app)
.post('/')
.send('command=john')
expect(handleSurveyListCommand).not.toHaveBeenCalled();
expect(handleSurveyRespondCommand).not.toHaveBeenCalled();
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
expect(consoleErrorSpy).toHaveBeenCalledWith(new Error('Command not found'));
});
});
and this is the error thrown
Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:
this test fails even if the only thing i do inside the route is to log something.
This is because it is not responding with the response while the request in the test case is waiting for some response, instead it tries to send the response.
router.post('/', async (req, res) => { try { const { command, text } = req.body; switch (command) { case 'abc': res.status(200).send("abc"); default: res.status(200).send("123"); } } catch (error) { res.status(500).send("unknown error"); } });Regarding undefined req.body -> use parsed body in application
app.use(express.bodyParser());