How to increase timeout for a single test case in mocha

前端 未结 8 1828
走了就别回头了
走了就别回头了 2020-11-28 01:59

I\'m submitting a network request in a test case, but this sometimes takes longer than 2 seconds (the default timeout).

How do I increase the timeout for a single te

相关标签:
8条回答
  • 2020-11-28 02:41

    If you wish to use es6 arrow functions you can add a .timeout(ms) to the end of your it definition:

    it('should not timeout', (done) => {
        doLongThing().then(() => {
            done();
        });
    }).timeout(5000);
    

    At least this works in Typescript.

    0 讨论(0)
  • 2020-11-28 02:45

    From command line:

    mocha -t 100000 test.js
    
    0 讨论(0)
  • 2020-11-28 02:55

    You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. Using Sinon, you can decouple the app from the network service, focusing your development efforts.

    0 讨论(0)
  • 2020-11-28 02:57

    (since I ran into this today)

    Be careful when using ES2015 fat arrow syntax:

    This will fail :

    it('accesses the network', done => {
    
      this.timeout(500); // will not work
    
      // *this* binding refers to parent function scope in fat arrow functions!
      // i.e. the *this* object of the describe function
    
      done();
    });
    

    EDIT: Why it fails:

    As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.

    Bottom line: Don't use arrow functions for functions that need an increased timeout.

    0 讨论(0)
  • 2020-11-28 03:02

    Here you go: http://mochajs.org/#test-level

    it('accesses the network', function(done){
      this.timeout(500);
      [Put network code here, with done() in the callback]
    })
    

    For arrow function use as follows:

    it('accesses the network', (done) => {
      [Put network code here, with done() in the callback]
    }).timeout(500);
    
    0 讨论(0)
  • 2020-11-28 03:02

    If you are using in NodeJS then you can set timeout in package.json

    "test": "mocha --timeout 10000"
    

    then you can run using npm like:

    npm test
    
    0 讨论(0)
提交回复
热议问题