[Ethereum] How to set the timeout for truffle test’s before block

mochatestingtruffletruffle-config

I'm running my tests on a private chain and some of them times out:

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

I tried to set timeout to the whole test or to the before part as per mocha documentation:

contract("looong tests", accounts => {
   this.timeout();

or

before( done => {
   this.timeout(40000);

I got this error:

  1)  "before all" hook:
     TypeError: _this.timeout is not a function

Adding -t command line parameter doesn't seem to have any effect:

truffle test myTest.js -t 40000
truffle test myTest.js --timeout 40000

I see an old pending fix in truffle: https://github.com/trufflesuite/truffle/issues/261

How can I increase the timeout for the before statement?

Adding timeout to individual test cases works but not for before statement 🙁

   it('one long test', () => {
        ....
    }).timeout(40000 ); 

EDIT:
I've a workaround for now, moved the code from before to the first test which I've made sync:

   it('should go to before block but can't set timeout there', done =>  {
        new Promise( async function (resolve, reject) {
          // my before code 
          resolve();
        }).then( res => {
         done();
        });
    }).timeout(40000 ); 

Best Answer

Add this in your Truffle configuration file (truffle.js or truffle-config.js):

mocha: {
    enableTimeouts: false,
    before_timeout: 120000 // Here is 2min but can be whatever timeout is suitable for you.
}

If you want to preserve timeouts (and even configure different timeouts for different tests), then simply follow the instructions here.

Related Topic