-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathindex.test.js
More file actions
370 lines (326 loc) · 10.6 KB
/
index.test.js
File metadata and controls
370 lines (326 loc) · 10.6 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/**
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @ts-ignore
import textExample from 'file-loader!./fixtures/example.txt';
// @ts-ignore
import jsonExample from 'file-loader!./fixtures/example.json.txt';
import axios from '../src/index.js';
import fetch from 'isomorphic-fetch';
describe('redaxios', () => {
describe('basic functionality', () => {
it('should return text and a 200 status for a simple GET request', async () => {
const req = axios(textExample);
expect(req).toBeInstanceOf(Promise);
const res = await req;
expect(res).toBeInstanceOf(Object);
expect(res.status).toEqual(200);
expect(res.data).toEqual('some example content');
});
it('should return a rejected promise for 404 responses', async () => {
const req = axios('/foo.txt');
expect(req).toBeInstanceOf(Promise);
const spy = jasmine.createSpy();
await req.catch(spy);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(jasmine.objectContaining({ status: 404 }));
});
});
describe('options.responseType', () => {
it('should parse responses as JSON by default', async () => {
const res = await axios.get(jsonExample);
expect(res.data).toEqual({ hello: 'world' });
});
it('should fall back to text for non-JSON by default', async () => {
const res = await axios.get(textExample);
expect(res.data).toEqual('some example content');
});
it('should force JSON for responseType:json', async () => {
const res = await axios.get(jsonExample, {
responseType: 'json'
});
expect(res.data).toEqual({ hello: 'world' });
});
it('should fall back to undefined for failed JSON parse', async () => {
const res = await axios.get(textExample, {
responseType: 'json'
});
expect(res.data).toEqual(undefined);
});
it('should still parse JSON when responseType:text', async () => {
// this is just how axios works
const res = await axios.get(jsonExample, {
responseType: 'text'
});
expect(res.data).toEqual({ hello: 'world' });
});
});
describe('options.baseURL', () => {
it('should resolve URLs relative to baseURL if provided', async () => {
const oldFetch = window.fetch;
try {
window.fetch = jasmine
.createSpy('fetch')
.and.returnValue(Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve('') }));
const req = axios.get('/bar', {
baseURL: 'http://foo'
});
expect(window.fetch).toHaveBeenCalledTimes(1);
expect(window.fetch).toHaveBeenCalledWith(
'http://foo/bar',
jasmine.objectContaining({
method: 'get',
headers: {},
body: undefined
})
);
const res = await req;
expect(res.status).toEqual(200);
} finally {
window.fetch = oldFetch;
}
});
it('should resolve baseURL for relative URIs', async () => {
const oldFetch = window.fetch;
try {
window.fetch = jasmine
.createSpy('fetch')
.and.returnValue(Promise.resolve({ ok: true, status: 200, text: () => Promise.resolve('') }));
const req = axios.get('/bar', {
baseURL: '/foo'
});
expect(window.fetch).toHaveBeenCalledTimes(1);
expect(window.fetch).toHaveBeenCalledWith(
'/foo/bar',
jasmine.objectContaining({
method: 'get',
headers: {},
body: undefined
})
);
const res = await req;
expect(res.status).toEqual(200);
} finally {
window.fetch = oldFetch;
}
});
});
describe('options.headers', () => {
it('should merge headers case-insensitively', async () => {
const oldFetch = window.fetch;
try {
const fetch = (window.fetch = jasmine.createSpy('fetch').and.returnValue(
Promise.resolve({
ok: true,
status: 200,
text: () => Promise.resolve('yep')
})
));
await axios('/', { headers: { 'x-foo': '2' } });
expect(fetch.calls.first().args[1].headers).toEqual({
'x-foo': '2'
});
fetch.calls.reset();
await axios('/', { headers: { 'x-foo': '2', 'X-Foo': '4' } });
expect(fetch.calls.first().args[1].headers).toEqual({
'x-foo': '4'
});
fetch.calls.reset();
const request = axios.create({
headers: {
'Base-Upper': 'base',
'base-lower': 'base'
}
});
await request('/');
expect(fetch.calls.first().args[1].headers).toEqual({
'base-upper': 'base',
'base-lower': 'base'
});
fetch.calls.reset();
await request('/', {
headers: {
'base-upper': 'replaced',
'BASE-LOWER': 'replaced'
}
});
expect(fetch.calls.first().args[1].headers).toEqual({
'base-upper': 'replaced',
'base-lower': 'replaced'
});
} finally {
window.fetch = oldFetch;
}
});
});
describe('options.body (request bodies)', () => {
let oldFetch, fetchMock;
beforeEach(() => {
oldFetch = window.fetch;
fetchMock = window.fetch = jasmine.createSpy('fetch').and.returnValue(
Promise.resolve({
ok: true,
status: 200,
text: () => Promise.resolve('yep')
})
);
});
afterEach(() => {
window.fetch = oldFetch;
});
it('should issue POST requests (with JSON body)', async () => {
const res = await axios.post('/foo', {
hello: 'world'
});
expect(fetchMock).toHaveBeenCalledWith(
'/foo',
jasmine.objectContaining({
method: 'post',
headers: {
'content-type': 'application/json'
},
body: '{"hello":"world"}'
})
);
expect(res.status).toEqual(200);
expect(res.data).toEqual('yep');
});
describe('FormData support', () => {
it('should not send JSON content-type when data contains FormData', async () => {
const formData = new FormData();
await axios.post('/foo', formData);
expect(fetchMock).toHaveBeenCalledWith(
'/foo',
jasmine.objectContaining({
body: formData,
headers: {}
})
);
});
it('should preserve global content-type option when using FormData', async () => {
const data = new FormData();
data.append('hello', 'world');
const res = await axios.post('/foo', data, { headers: { 'content-type': 'multipart/form-data' } });
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
'/foo',
jasmine.objectContaining({
method: 'post',
headers: {
'content-type': 'multipart/form-data'
},
body: data
})
);
expect(res.status).toEqual(200);
expect(res.data).toEqual('yep');
});
});
});
describe('options.fetch', () => {
it('should accept a custom fetch implementation', async () => {
const req = axios.get(jsonExample, { fetch });
expect(req).toBeInstanceOf(Promise);
const res = await req;
expect(res).toBeInstanceOf(Object);
expect(res.status).toEqual(200);
expect(res.data).toEqual({ hello: 'world' });
});
});
describe('options.params & options.paramsSerializer', () => {
let oldFetch, fetchMock;
beforeEach(() => {
oldFetch = window.fetch;
fetchMock = window.fetch = jasmine.createSpy('fetch').and.returnValue(Promise.resolve());
});
afterEach(() => {
window.fetch = oldFetch;
});
it('should not serialize missing params', async () => {
axios.get('/foo');
expect(fetchMock).toHaveBeenCalledWith('/foo', jasmine.any(Object));
});
it('should serialize numeric and boolean params', async () => {
const params = { a: 1, b: true };
axios.get('/foo', { params });
expect(fetchMock).toHaveBeenCalledWith('/foo?a=1&b=true', jasmine.any(Object));
});
it('should merge params into existing url querystring', async () => {
const params = { a: 1, b: true };
axios.get('/foo?c=42', { params });
expect(fetchMock).toHaveBeenCalledWith('/foo?c=42&a=1&b=true', jasmine.any(Object));
});
it('should accept a URLSearchParams instance', async () => {
const params = new URLSearchParams({ d: 'test' });
axios.get('/foo', { params });
expect(fetchMock).toHaveBeenCalledWith('/foo?d=test', jasmine.any(Object));
});
it('should accept a custom paramsSerializer function', async () => {
const params = { a: 1, b: true };
const paramsSerializer = (params) => 'e=iamthelaw';
axios.get('/foo', { params, paramsSerializer });
expect(fetchMock).toHaveBeenCalledWith('/foo?e=iamthelaw', jasmine.any(Object));
});
});
describe('static helpers', () => {
it(`#all should work`, async () => {
const result = await axios.all([Promise.resolve('hello'), Promise.resolve('world')]);
expect(result).toEqual(['hello', 'world']);
});
it(`#spread should work`, async () => {
const result = await axios.all([Promise.resolve('hello'), Promise.resolve('world')]).then(
axios.spread((item1, item2) => {
return `${item1} ${item2}`;
})
);
expect(result).toEqual('hello world');
});
});
describe('Request cancellation using options.cancelToken', () => {
it('should cancel a request when cancelToken is passed as source.token', async () => {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const axiosGet = axios.get(jsonExample, {
cancelToken: source.token
});
source.cancel();
const spy = jasmine.createSpy();
await axiosGet.catch(spy);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(
jasmine.objectContaining({ code: 20, message: 'The user aborted a request.', name: 'AbortError' })
);
});
it('should cancel a request when cancelToken is passed as instance CreateToken', async () => {
const CancelToken = axios.CancelToken;
let cancel;
const axiosGet = axios.get(jsonExample, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
})
});
cancel();
const spy = jasmine.createSpy();
let error;
await axiosGet.catch((e) => ((error = e), spy(e)));
expect(axios.isCancel(error)).toBeTruthy(true);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(
jasmine.objectContaining({ code: 20, message: 'The user aborted a request.', name: 'AbortError' })
);
});
it('should throw TypeError if no executor function is passed to CancelToken constructor', () => {
const CancelToken = axios.CancelToken;
expect(() => new CancelToken()).toThrowError('executor must be a function.');
});
});
});