Skip to content

Commit e0a1206

Browse files
test: add Node unit tests for toFormData and refactor buildURL to avoid param reassignment (#7272)
Co-authored-by: Jay <[email protected]>
1 parent f7bdcd1 commit e0a1206

File tree

2 files changed

+60
-10
lines changed

2 files changed

+60
-10
lines changed

lib/helpers/buildURL.js

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,29 +29,26 @@ function encode(val) {
2929
* @returns {string} The formatted url
3030
*/
3131
export default function buildURL(url, params, options) {
32-
/*eslint no-param-reassign:0*/
3332
if (!params) {
3433
return url;
3534
}
36-
35+
3736
const _encode = options && options.encode || encode;
3837

39-
if (utils.isFunction(options)) {
40-
options = {
41-
serialize: options
42-
};
43-
}
38+
const _options = utils.isFunction(options) ? {
39+
serialize: options
40+
} : options;
4441

45-
const serializeFn = options && options.serialize;
42+
const serializeFn = _options && _options.serialize;
4643

4744
let serializedParams;
4845

4946
if (serializeFn) {
50-
serializedParams = serializeFn(params, options);
47+
serializedParams = serializeFn(params, _options);
5148
} else {
5249
serializedParams = utils.isURLSearchParams(params) ?
5350
params.toString() :
54-
new AxiosURLSearchParams(params, options).toString(_encode);
51+
new AxiosURLSearchParams(params, _options).toString(_encode);
5552
}
5653

5754
if (serializedParams) {

test/unit/helpers/toFormData.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import assert from 'assert';
2+
import toFormData from '../../../lib/helpers/toFormData.js';
3+
import FormData from 'form-data';
4+
5+
describe('helpers::toFormData', function () {
6+
it('should convert a flat object to FormData', function () {
7+
const data = {
8+
foo: 'bar',
9+
baz: 123
10+
};
11+
12+
const formData = toFormData(data, new FormData());
13+
14+
assert.ok(formData instanceof FormData);
15+
// form-data package specific checks
16+
assert.ok(formData._streams.length > 0);
17+
});
18+
19+
it('should convert a nested object to FormData', function () {
20+
const data = {
21+
foo: {
22+
bar: 'baz'
23+
}
24+
};
25+
26+
const formData = toFormData(data, new FormData());
27+
28+
assert.ok(formData instanceof FormData);
29+
});
30+
31+
it('should throw Error on circular reference', function () {
32+
const data = {
33+
foo: 'bar'
34+
};
35+
data.self = data;
36+
37+
try {
38+
toFormData(data, new FormData());
39+
assert.fail('Should have thrown an error');
40+
} catch (e) {
41+
assert.strictEqual(e.message, 'Circular reference detected in self');
42+
}
43+
});
44+
45+
it('should handle arrays', function () {
46+
const data = {
47+
arr: [1, 2, 3]
48+
};
49+
50+
const formData = toFormData(data, new FormData());
51+
assert.ok(formData instanceof FormData);
52+
});
53+
});

0 commit comments

Comments
 (0)