supertest times out on post request

Viewed 329

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.

1 Answers

This is because you are not responding back with the response while the request in test case is waiting for some response, instead return try sending 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 req.body undefined ->use body parsed in app

app.use(express.bodyParser());
Related