【问题标题】:how test for no content, while we have 204 NO CONTENT status, as there is no 'Content-Type' header at all?如何测试没有内容,而我们有 204 NO CONTENT 状态,因为根本没有“Content-Type”标头?
【发布时间】:2016-03-28 05:54:22
【问题描述】:

当拥有200 OK 状态时,很容易测试Content-Type。我们这样做:

it('should list All permissions on /permissions GET', (done)=> {
    supertest(app)
        .get('/permissions')
        .expect('Content-Type', /json/)
        .end( (err, res)=> {
            // SOME CODE HERE
            done(err)
        })
})

所以.expect('Content-Type', /json/) 为我完成这项工作。现在,当我有一个DELETE 请求时,我不想返回任何内容。 204 NO CONTENT 的状态,没有任何内容。

但是当没有内容时,所以Content-Type不存在。正确的方法是检查Content-Type 标头的存在吗?如何使用supertest 做到这一点?

感谢您的宝贵时间。谢谢。

【问题讨论】:

    标签: node.js mocha.js supertest


    【解决方案1】:

    如果要检查标头不是否存在,可以使用基于通用函数的expect() 进行自定义断言:

    .expect(function(res) {
      if (res.headers['Content-Type'])
        return new Error('Unexpected content-type!');
    })
    

    如果您还想检查是否没有正文:

    .expect(204, '')
    

    【讨论】:

    • 我可以有没有内容的正文吗?我的意思是你输入答案的第二个就足够了,不需要自定义断言,对吧?
    【解决方案2】:

    当您从服务器发回HTTP 204 status code 时,正文中不应有任何内容。大多数服务器实现,即。 express,restify 将不包含此状态代码的 Content-Type 标头。

    对于使用 supertest 的测试,您应该只使用期望检查 HTTP 状态代码。 即:

    .expect(204)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 2014-09-13
      • 2012-01-21
      • 2013-06-09
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      相关资源
      最近更新 更多