在mocha中获得超时错误超过

时间:2018-03-13 10:49:38

标签: node.js http promise timeout mocha

mocha错误:超过2000ms的超时,对于异步测试和挂钩,确保在此测试中调用done()回调。如果退回承诺,请确保它解决。

这是我在尝试获得回复时遇到的错误,

这是我的index.js文件,其中我导出函数

exports.info = function(callback) { 
    var https = require('https'); 
    var options = {
     host: 'api.github.com', 
     path: '/repos/sayanee/build-podcast', 
     method: 'GET', 
     headers: { 'User-Agent': 'sayanee' } }; 
    var str = '';

    https.request(options, function(response) { 
    response.on('data', function(data) { 
        str += data; 
    });

     response.on('end', function() {
       callback(JSON.parse(str));
     })

     response.on('error', function(error) {
       console.log(error);
       callback();
    })    
})    .end();
}

这是我的索引文件,其中我描述了测试用例

function asyncFunction() {
    return new Promise(resolve => {
        setTimeout(resolve, 5000);
    });
}
describe('Github info', function() {
it.only('returns repo info from github', async function() { 
    //this.timeout(5000);
    await asyncFunction();
    word.info(function(reply) { 
        console.log("er")
        expect(reply.language).to.equal('JavaScript'); 
        expect(reply.watchers).to.equal(157); 
        console.log('RECEIVED'); 

    }); 
    console.log('HELLO'); })
});

2 个答案:

答案 0 :(得分:1)

Mocha也支持异步测试,方法是将done回调作为参数传递给您需要在测试端调用的it

describe("Github info", function () {
    it.only("returns repo info from github", function (done) {
        // set long timeout to be sure word.info finish 
        this.timeout(5000);
        word.info(function (reply) {
            console.log("er");
            expect(reply.language).to.equal("JavaScript");
            expect(reply.watchers).to.equal(157);
            console.log("RECEIVED");
            // call done at end
            done();
        });
        console.log("HELLO");
    });
});

答案 1 :(得分:0)

回答在您的问题中。 2秒后,Mocha设置为超时。

您要求在 2000ms

内完成请求

要么增加Mocha timeout示例:

mocha -t 300000

编辑

您无法使用与async/await

混淆的callbacks
// Wrap your function into a promise
wordInfoPromise() {
  return new Promise((resolve, reject) => {
    word.info((ret) => {
      if (!ret) return reject();

      return resolve(ret);
    });
  });
}
it('returns repo info from github', async function() { 
    //this.timeout(5000);
    await asyncFunction();

    const reply = await wordInfoPromise();

    console.log("er")

    expect(reply.language).to.equal('JavaScript'); 

    expect(reply.watchers).to.equal(157); 

    console.log('RECEIVED'); 

    console.log('HELLO'); })
});

编辑2:

    const req = https.request(options, (res) => {
      res.on('data', (d) => {
        str += data;
      });

      res.on('end', () => {
        resolve(str);
      });
    });

    req.on('error', (e) => {
      reject();
    });

    req.end();