我正在使用Nock和Mocha,并想检查请求中是否存在特定的标头。我不在意其他标头,也不在意我要检查的标头的具体内容。有没有一种简单的方法来实现这个功能?
.matchHeader()当特定的标头不存在时会通过,而reqheaders则会失败,除非我指定所有标头字段。
reqheaders
是正确的方法。
我不确定您遇到了哪个问题,但并非所有标头都需要提供。只需要为匹配所需的标头。
reqheaders
的另一个好处是该值可以是返回布尔值的函数。由于您不关心标头的实际值,因此返回 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()