3

I'm running a test using mocha

it('should allow a POST to /users', async function () {
        
        const res = await request.post('/users').send(firstUserBody);
    
        expect(res.status).to.equal(201);
        expect(res.body).not.to.be.empty;
        expect(res.body).to.be.an('object');
        expect(res.body.id).to.be.a('string');
        firstUserIdTest = res.body.id;
        
    });

but i have an error

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

If I do it using done() the function is not async but it should be

it('should allow a POST to /users', async function (done) {

        const res = await request.post('/users').send(firstUserBody);

        expect(res.status).to.equal(201);
        expect(res.body).not.to.be.empty;
        expect(res.body).to.be.an('object');
        expect(res.body.id).to.be.a('string');
        firstUserIdTest = res.body.id;
        done();
    });

what should i do ?

yilmazoncum
  • 39
  • 1
  • 4

1 Answers1

3

There are two approaches of setting timeouts in Mocha:

(I would use a minimum of 20s when testing API calls)

  1. Inside the test or describe block

    describe('a suite of tests', function() {
      this.timeout(20000);
      ...
    

    (be careful not to use an arrow function as that will cause this. to not work)

    See: https://mochajs.org/#timeouts

  2. Config level - .mocharc.js file or flag during runtime --timeout 20000 or even setting options with API (mocha.setup()).

    I prefer using .mocharc.js. where you can put something like:

    module.exports = {
      bail: true,
      timeout: 5 * 60 * 1000, // 5 minute timeout
      spec: ['specs/']
    };
    

Documentation and examples:

https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js

https://mochajs.org/#configuring-mocha-nodejs

https://mochajs.org/#-timeout-ms-t-ms

PS You should not need the done() with async functions

Dmitri R117
  • 2,502
  • 23
  • 20