javascriptnode.jstypescriptmocha.js

How to set timeout in Mocha root-level hooks?


I want to set a timeout for the root-level hook for Mocha testing.

My root-level hook looks like this, in test/setup.ts:

import * as database from '../src/database/_db'

export const mochaHooks = {
    /* Connect to the DB before running any tests */
    beforeAll(done: () => void) {
        database.initialize(done)
    },
    
    /* Close the DB connect after all tests finished */
    afterAll(done: () => void) {
        database.close(done);
    }
};

and this is loaded via --require test/setup.ts. The DB connection takes a long time so I'd like to increase the timeout value.

Running Mocha with -t 10000 works but that also sets timeouts for every test.

I've also tried to add this.timeout(3000) in BeforeAll but got ✖ ERROR: test/setup.ts:10:14 - error TS2339: Property 'timeout' does not exist on type '{ beforeAll(done: () => void): void; afterAll(done: () => void): void; }'.


Solution

  • From the doc ARROW FUNCTIONS:

    Passing arrow functions (aka “lambdas”) to Mocha is discouraged. Lambdas lexically bind this and cannot access the Mocha context.

    Test context isn't being bound when using arrow functions. So you can't use this.timeout().

    You should change the arrow function to function declaration which consists of the function keyword.