mirror of
https://github.com/tenrok/axios.git
synced 2026-05-15 11:59:42 +03:00
test: add Node unit tests for toFormData and refactor buildURL to avoid param reassignment (#7272)
Co-authored-by: Jay <jasonsaayman@gmail.com>
This commit is contained in:
+7
-10
@@ -29,29 +29,26 @@ function encode(val) {
|
||||
* @returns {string} The formatted url
|
||||
*/
|
||||
export default function buildURL(url, params, options) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
if (!params) {
|
||||
return url;
|
||||
}
|
||||
|
||||
|
||||
const _encode = options && options.encode || encode;
|
||||
|
||||
if (utils.isFunction(options)) {
|
||||
options = {
|
||||
serialize: options
|
||||
};
|
||||
}
|
||||
const _options = utils.isFunction(options) ? {
|
||||
serialize: options
|
||||
} : options;
|
||||
|
||||
const serializeFn = options && options.serialize;
|
||||
const serializeFn = _options && _options.serialize;
|
||||
|
||||
let serializedParams;
|
||||
|
||||
if (serializeFn) {
|
||||
serializedParams = serializeFn(params, options);
|
||||
serializedParams = serializeFn(params, _options);
|
||||
} else {
|
||||
serializedParams = utils.isURLSearchParams(params) ?
|
||||
params.toString() :
|
||||
new AxiosURLSearchParams(params, options).toString(_encode);
|
||||
new AxiosURLSearchParams(params, _options).toString(_encode);
|
||||
}
|
||||
|
||||
if (serializedParams) {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from 'assert';
|
||||
import toFormData from '../../../lib/helpers/toFormData.js';
|
||||
import FormData from 'form-data';
|
||||
|
||||
describe('helpers::toFormData', function () {
|
||||
it('should convert a flat object to FormData', function () {
|
||||
const data = {
|
||||
foo: 'bar',
|
||||
baz: 123
|
||||
};
|
||||
|
||||
const formData = toFormData(data, new FormData());
|
||||
|
||||
assert.ok(formData instanceof FormData);
|
||||
// form-data package specific checks
|
||||
assert.ok(formData._streams.length > 0);
|
||||
});
|
||||
|
||||
it('should convert a nested object to FormData', function () {
|
||||
const data = {
|
||||
foo: {
|
||||
bar: 'baz'
|
||||
}
|
||||
};
|
||||
|
||||
const formData = toFormData(data, new FormData());
|
||||
|
||||
assert.ok(formData instanceof FormData);
|
||||
});
|
||||
|
||||
it('should throw Error on circular reference', function () {
|
||||
const data = {
|
||||
foo: 'bar'
|
||||
};
|
||||
data.self = data;
|
||||
|
||||
try {
|
||||
toFormData(data, new FormData());
|
||||
assert.fail('Should have thrown an error');
|
||||
} catch (e) {
|
||||
assert.strictEqual(e.message, 'Circular reference detected in self');
|
||||
}
|
||||
});
|
||||
|
||||
it('should handle arrays', function () {
|
||||
const data = {
|
||||
arr: [1, 2, 3]
|
||||
};
|
||||
|
||||
const formData = toFormData(data, new FormData());
|
||||
assert.ok(formData instanceof FormData);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user