How to set timeout on before hook in mocha?

后端 未结 4 1656
一生所求
一生所求 2021-01-03 17:32

I want to set timeout value on before hook in mocha test cases. I know I can do that by adding -t 10000 on the command line of mocha but this will change every

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 18:22

    as instructed at https://mochajs.org/#hook-level, you have to use a regular function call to set the timeout.

    before(function(done) {
      this.timeout(3000); // A very long environment setup.
      setTimeout(done, 2500);
    });
    

    if you insist on use arrow or async function in the hook. You may do it this way:

    before(function (done) {
      this.timeout(3000);
      (async () => {
        await initilizeWithPromise();
      })().then(done);
    });
    

    It is quite helpful and nice-looking if you got multiple async calls to be resolved in the hook.

    updated: fuction def works well with async too. So this hook can be upgraded to

    before(async function () {
      this.timeout(3000);
      await initilizeWithPromise();      
    });
    

    So it provides benefits from both this and await.

    By the way, mocha works pretty fine with promises nowadays. If timeout is not a concern. Just do this:

    before(async () => {
      await initilizeWithPromise();
    });
    

提交回复
热议问题