关于异步:测试Mocha / supertest / expect MEAN-stack HTTP请求已完成4秒延迟

Testing Mocha/supertest/expect MEAN-stack HTTP Request 4 seconds delay done

我正在使用Mocha / supertest / expect库在MEAN-Stack中测试HTTP请求,该过程需要4秒钟才能返回:

1
2
3
4
5
6
7
8
9
it('should return product data', (done) => {
    request(app)
    .get('/P/Product')
    .expect(200)
    .expect((res) => {
        expect(res.body[0]._id).toEqual('123456789')
    })
    .end(done);
});

HTTP请求完成后,该函数应在最后执行"完成"回调。 但是我得到了错误:

1
2
3
1) should return product data:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure"done()" is called; if returning a
Promise, ensure it resolves.

我认为它适用于未嵌套的预期呼叫。 像上面的示例一样,我该如何在其他期望调用中嵌套期望调用呢?


可能来自请求的响应时间太长,导致Mocha的默认2秒测试超时发生。 可能尝试从CLI到URL的cURL,以查看您返回或提高测试的Mocha测试时间阈值的时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
describe('testing', function() {
    // This applies the timeout of 5 seconds to each test.
    this.timeout(5000);

    it('should return product data', function() {
       // This applies a timeout of 5 seconds for this test only
       this.timeout(5000);
       request(app)
           .get('/P/Product')
           .expect(200)
           .expect((res) => {
                expect(res.body[0]._id).toEqual('123456789')
           })
           .end(done);
       });
});

如果您认为expect调用链导致超时问题,则可以使用诺言方法。

1
2
3
4
5
6
7
8
it('should return product data', () => {
   request(app)
   .get('/P/Product')
   .then((res) => {
       expect(res.status).to.equal(200);
       expect(res.body[0]._id).to.equal('123456789');
   })
});


我得到了解决方案,问题是使用箭头功能:(done)=>{...},而不是正常的回调,它的工作方式如下:

1
2
3
4
5
6
7
it('should async square a number', function(done) {  
    this.timeout(2005);
    utils.asyncSquare(5, (res) => {
      expect(res).toBe(25).toBeA('number');
      done();
    });
  });

或者,如果您在打包测试脚本中全局设置超时,它也可以使用:

1
"test":"mocha --timeout 3000 **/*.test.js",