-
Notifications
You must be signed in to change notification settings - Fork 18
/
multi-part-mapper.test.js
80 lines (71 loc) · 2.12 KB
/
multi-part-mapper.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict';
// This is using file system APIs, no need to run it in a browser.
if (typeof document !== 'undefined') return;
const fs = require('fs');
const assert = require('assertive');
const FormData = require('form-data');
const Gofer = require('../');
const defaultOptions = require('./mock-service');
function appendAll(form, formData) {
function appendOne(field, value) {
form.append(field, value);
}
for (const key in formData) {
if (!formData.hasOwnProperty(key)) continue;
const formValue = formData[key];
if (Array.isArray(formValue)) {
formValue.forEach(appendOne.bind(null, key));
} else {
appendOne(key, formValue);
}
}
}
describe('fetch: multi-part via form-data', () => {
// This serves as a POC that more "exotic" features can be
// added via option mappers without requiring support in Gofer.
const client = new Gofer().with(defaultOptions);
client.registerEndpoint('echo', fetch => {
return function (options) {
return fetch('/echo', options).json();
};
});
client.addOptionMapper(options => {
const formData = options.formData;
if (formData) {
delete options.formData;
const form = (options.body = new FormData());
appendAll(form, formData);
options.headers = options.headers || {};
Object.assign(options.headers, form.getHeaders());
}
return options;
});
it('can send a complex form with file uploads', () => {
const file = fs.createReadStream('package.json');
return client
.echo({
formData: {
str: 'I💖🍕',
myFile: file,
},
method: 'PUT',
})
.then(echo => {
assert.equal('PUT', echo.method);
assert.match(
/multipart\/form-data; boundary=/,
echo.headers['content-type']
);
assert.include(
'Content-Disposition: form-data; name="myFile"; filename="package.json"',
echo.body
);
assert.include(
['Content-Disposition: form-data; name="str"', '', 'I💖🍕'].join(
'\r\n'
),
echo.body
);
});
});
});