Nock record outputs array of hex values instead of plain JSON when response is encoded
See original GitHub issueRelated: https://github.com/nock/nock/issues/457#issuecomment-419480974
What is the expected behavior?
When recording responses which are compressed and chunked, e.g. Content-Encoding: 'gzip'
and Transfer-Encoding: 'chunked'
, I was expecting the generated fixture to decompress and combine the chunks into the human readable response; this would then allow us to remove sensitive information from the response and modify it to satisfy scenarios which are hard to reproduce against the real APIs.
What is the actual behavior? The fixtures response is an array of hex values.
Possible solution I’m working around this by modifying the nockDefs like this:
onst { ungzip } = require('node-gzip');
try {
if (Array.isArray(def.response)) { // NOTE: This is a v. naive check
def.response = JSON.parse(
(await ungzip(Buffer.from(def.response.join(''), 'hex'))).toString(
'utf-8'
)
);
}
} catch (ex) {
console.warn('Failed to decode response');
}
If this is in fact a bug then it’d be good to fix it in nock itself – if it’s as intended, i.e. the nock is technically returning the exact same response as the real server, then perhaps an option could be passed to nock record / nock.back
to have it output the decompressed response?
How to reproduce the issue The issue can be reproduced by recording an API which returns compressed, chunked JSON.
Does the bug have a test case? https://github.com/richardscarrott/nock-record-chunked-encoding
Versions
Software | Version(s) |
---|---|
Nock | 9.6.1 |
Node | 10.5.0 |
Issue Analytics
- State:
- Created 5 years ago
- Reactions:12
- Comments:9 (2 by maintainers)
@richardscarrott thanks for pointing me in the right direction with this. The additional problem I had to figure out was that I needed to re-gzip after normalizing. This was because https://github.com/octokit/rest.js expects the response to be gzipped.
To work with
nockBack
, without changing nock internally, here is what I did in theafterRecord
callback:FYI, this is the complete
afterNock
function I’m using