Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

mocha.js - How to set timeout on before hook in mocha?

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 test cases timeout value. I want to find a way to change the timeout programmatically below is my code:

describe('test  ', () => {

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

it will complain about the line this.timeout(1000) that timeout is not defined. How to set the timeout on before hook.

question from:https://stackoverflow.com/questions/41949895/how-to-set-timeout-on-before-hook-in-mocha

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to set a timeout in your describe block rather than in the hook if you want it to affect all the tests in the describe. However, you need to use a "regular" function as the callback to describe rather than an arrow function:

describe('test', function () {
  this.timeout(10000);

  before(...);

  it(...);
});

In all places where you want to use this in a callback you pass to Mocha you cannot use an arrow function. You must use a "regular" function which has its own this value that can be set by Mocha. If you use an arrow function, the value of this won't be what Mocha wants it to be and your code will fail.

You could set a different timeout for your before hook but there are two things to consider:

  1. Here too you'd need to use a "regular" function rather than an arrow function so:
before(function (done) { 
  this.timeout(10000);
  1. This would set a timeout only for the before hook and would not affect your tests.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...