Skip to content

Commit

Permalink
Testing and cleanup of transformResponse (axios#3377)
Browse files Browse the repository at this point in the history
- Tests for transformResponse
 - Remove eslint error by renaming the var
 - Test that there data a length to avoid JSON.parse headache
 - Use `util.isString()` over `typeof`

Co-authored-by: Jay <jasonsaayman@gmail.com>
  • Loading branch information
timemachine3030 and jasonsaayman authored Mar 24, 2021
1 parent bd146d4 commit 68c0a7f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
8 changes: 4 additions & 4 deletions lib/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ var defaults = {
}],

transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
var result = data;
if (utils.isString(result) && result.length) {
try {
data = JSON.parse(data);
result = JSON.parse(result);
} catch (e) { /* Ignore */ }
}
return data;
return result;
}],

/**
Expand Down
30 changes: 30 additions & 0 deletions test/unit/defaults/transformReponse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
var defaults = require('../../../lib/defaults');
var transformData = require('../../../lib/core/transformData');
var assert = require('assert');

describe('transformResponse', function () {
describe('200 request', function () {
it('parses json', function () {
var data = '{"message": "hello, world"}';
var result = transformData(data, {'content-type': 'application/json'}, defaults.transformResponse);
assert.strictEqual(result.message, 'hello, world');
});
it('ignores XML', function () {
var data = '<message>hello, world</message>';
var result = transformData(data, {'content-type': 'text/xml'}, defaults.transformResponse);
assert.strictEqual(result, data);
});
});
describe('204 request', function () {
it('does not parse the empty string', function () {
var data = '';
var result = transformData(data, {'content-type': undefined}, defaults.transformResponse);
assert.strictEqual(result, '');
});
it('does not parse undefined', function () {
var data = undefined;
var result = transformData(data, {'content-type': undefined}, defaults.transformResponse);
assert.strictEqual(result, data);
});
});
});

0 comments on commit 68c0a7f

Please sign in to comment.