如何增加超时摩卡一个测试用例(How to increase timeout for a singl

2019-08-22 07:40发布

我提交在测试情况下的网络的请求,但这个有时需要超过2秒(默认超时)。

如何增加一个测试用例超时?

Answer 1:

在这里你去: http://mochajs.org/#test-level

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

对于箭头功能使用方法如下:

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


Answer 2:

如果您想使用ES6箭头功能,您可以在添加.timeout(ms)到您的结束it的定义:

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

至少,这工作在打字稿。



Answer 3:

(因为我遇到了这个今天)

使用ES2015胖箭头语法时要小心:

这将失败:

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();
});

编辑:失败的原因:

作为@atoth提到的意见, 胖箭头函数没有自己的这种结合。 因此,它不可能为的功能结合到这种回调并提供超时功能。

底线 :不要使用箭头功能需要增加的超时功能。



Answer 4:

如果您在使用的NodeJS,那么你可以设置的package.json超时

"test": "mocha --timeout 10000"

然后你可以运行使用NPM,如:

npm test


Answer 5:

从命令行:

mocha -t 100000 test.js


Answer 6:

你可能也想采取不同的方法,并更换调用网络资源与存根或模拟对象。 使用兴农 ,您可以从网络服务解耦应用,重点开发工作。



Answer 7:

有关测试navegation Express

const request = require('supertest');
const server = require('../bin/www');

describe('navegation', () => {
    it('login page', function(done) {
        this.timeout(4000);
        const timeOut = setTimeout(done, 3500);

        request(server)
            .get('/login')
            .expect(200)
            .then(res => {
                res.text.should.include('Login');
                clearTimeout(timeOut);
                done();
            })
            .catch(err => {
                console.log(this.test.fullTitle(), err);
                clearTimeout(timeOut);
                done(err);
            });
    });
});

在示例中,测试时间为4000(4S)。

注: setTimeout(done, 3500)比较小done的测试,但的时间内调用clearTimeout(timeOut)它避免使用比所有这些时间。



文章来源: How to increase timeout for a single test case in mocha
标签: mocha