【问题标题】:What is the purpose/nature of 'done()' in Supertest?Supertest中'done()'的目的/性质是什么?
【发布时间】:2020-07-25 20:09:27
【问题描述】:

在(非常有限的)documentation of Supertest 中有代码示例,其中传递了一个名为 done() 的回调函数:

describe('GET /user', function() {
  it('responds with json', function(done) {
    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });
});

这个done() 回调的目的/性质是什么?

【问题讨论】:

    标签: node.js supertest


    【解决方案1】:

    您的请求是异步的。

    这意味着,除非您能够等待它,否则从第 2 行开始的函数将立即退出。然后 Mocha 将继续进行其他测试,然后突然间,请求承诺将履行并做一些事情,而 mocha 甚至不再查看您的“使用 json 响应”规范。

    您试图实现的行为是执行请求,等待响应,然后测试是否为 200。

    等待响应的方式有3种:

    1. 完成

    通过将 done 放入你的 function(done) 调用中,测试框架知道它应该等到 done 被调用后再完成测试。

    1. 返回

    正如您在自述文件 (https://github.com/visionmedia/supertest#readme) 中看到的,还可以选择退货:

    describe('GET /user', function() {
      it('responds with json', function() {
        return request(app)
          .get('/user')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200);
      });
    });
    

    因为 mocha 会等待所有返回的承诺。

    1. 异步
    describe('GET /user', function() {
      it('responds with json', async function() {
        await request(app)
          .get('/user')
          .set('Accept', 'application/json')
          .expect('Content-Type', /json/)
          .expect(200);
      });
    });
    

    【讨论】:

    • 这是否意味着done 是 Mocha/Jest 功能而不是 Supertest 功能?
    • 另外,在你的最后两个代码示例中:done 是否应该被省略?
    • 你完全正确! done 是 mocha 功能,在其他两个示例中应该省略 done。更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    相关资源
    最近更新 更多