Nock.js:如何检查 header 是否存在?

Nock.js: how do I check for the existence of a header?

我正在将 Nock 与 Mocha 一起使用,并想检查请求中是否存在某些 header。我不关心其他 headers,也不关心我正在检查其存在的 headers 的具体内容。是否有捷径可寻? .matchHeader() 在特定 header 不存在时通过,而 reqheaders 失败,除非我指定所有 header 字段。

reqheaders 是正确的方法。

我不确定您遇到了什么问题,但并非所有 header 都需要提供。只有匹配所需的那些。

reqheaders 的另一个不错的特性是值可以是返回布尔值的函数。由于您不关心 header 的实际值,如果 header 简单存在,则返回 true 具有匹配的效果。

const scope = nock('http://www.example.com', {
  reqheaders: {
    'x-one': () => true,
  }
}).get('/').reply(200, 'match!')


const reqOpts = {
  hostname: 'www.example.com',
  path: '/',
  method: 'GET',
  headers: {
    'X-One': 'hello world',
    'X-Two': 'foo bar',
    'Content-Type': 'application/json',
  }
}

const req = http.request(reqOpts, res => {
  console.log("##### res status", res.statusCode)

  res.on('data', (chunk) => {
    console.log("##### chunk", chunk.toString())
  })
})

req.end()
scope.done()