forked from parse-community/Parse-SDK-JS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParseFile-test.js
976 lines (881 loc) · 31.1 KB
/
ParseFile-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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
jest.autoMockOff();
jest.mock('http');
jest.mock('https');
jest.mock('../ParseACL');
const ParseError = require('../ParseError').default;
const ParseFile = require('../ParseFile').default;
const b64Digit = require('../ParseFile').b64Digit;
const ParseObject = require('../ParseObject').default;
const CoreManager = require('../CoreManager').default;
const EventEmitter = require('../EventEmitter').default;
const mockHttp = require('http');
const mockHttps = require('https');
const mockLocalDatastore = {
_updateLocalIdForObject: jest.fn((_localId, /** @type {ParseObject}*/ object) => {
if (!mockLocalDatastore.isEnabled) {
return;
}
// (Taken from LocalDataStore source) This fails for nested objects that are not ParseObject
/* eslint-disable @typescript-eslint/no-unused-vars */
const objectKey = mockLocalDatastore.getKeyForObject(object);
}),
_updateObjectIfPinned: jest.fn(),
getKeyForObject: jest.fn(object => {
// (Taken from LocalDataStore source) This fails for nested objects that are not ParseObject
const OBJECT_PREFIX = 'Parse_LDS_';
const objectId = object.objectId || object._getId();
return `${OBJECT_PREFIX}${object.className}_${objectId}`;
}),
};
jest.setMock('../LocalDatastore', mockLocalDatastore);
function generateSaveMock(prefix) {
return function (name, payload, options) {
if (options && typeof options.progress === 'function') {
options.progress(0.5, 5, 10, { type: 'upload' });
}
return Promise.resolve({
name: name,
url: prefix + name,
});
};
}
const defaultController = CoreManager.getFileController();
describe('ParseFile', () => {
beforeEach(() => {
ParseObject.enableSingleInstance();
jest.clearAllMocks();
CoreManager.setFileController({
saveFile: generateSaveMock('http://files.parsetfss.com/a/'),
saveBase64: generateSaveMock('http://files.parsetfss.com/a/'),
download: () =>
Promise.resolve({
base64: 'ParseA==',
contentType: 'image/png',
}),
});
});
afterEach(() => {
process.env.PARSE_BUILD = 'node';
});
it('can create files with base64 encoding (no padding)', () => {
const file = new ParseFile('parse.txt', { base64: 'YWJj' });
expect(file._source.base64).toBe('YWJj');
expect(file._source.type).toBe('text/plain');
expect(file._data).toBe('YWJj');
});
it('can create files with base64 encoding (1 padding)', () => {
const file = new ParseFile('parse.txt', { base64: 'YWI=' });
expect(file._source.base64).toBe('YWI=');
expect(file._source.type).toBe('text/plain');
expect(file._data).toBe('YWI=');
});
it('can create files with base64 encoding (2 padding)', () => {
const file = new ParseFile('parse.txt', { base64: 'ParseA==' });
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('text/plain');
expect(file._data).toBe('ParseA==');
});
it('can set the default type to be text/plain when using base64', () => {
const file = new ParseFile('parse.txt', {
base64: 'data:;base64,ParseA==',
});
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('text/plain');
expect(file._data).toBe('ParseA==');
});
it('can extract data type from base64', () => {
const file = new ParseFile('parse.png', {
base64: 'data:image/png;base64,ParseA==',
});
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('image/png');
expect(file._data).toBe('ParseA==');
});
it('can extract data type from base64 with a filename parameter', () => {
const file = new ParseFile('parse.pdf', {
base64: 'data:application/pdf;filename=parse.pdf;base64,ParseA==',
});
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('application/pdf');
expect(file._data).toBe('ParseA==');
});
it('can create files with file uri', () => {
const file = new ParseFile('parse-image', {
uri: 'http://example.com/image.png',
});
expect(file._source.format).toBe('uri');
expect(file._source.uri).toBe('http://example.com/image.png');
});
it('can extract data type from base64 with data type containing a number', () => {
const file = new ParseFile('parse.m4a', {
base64: 'data:audio/m4a;base64,ParseA==',
});
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('audio/m4a');
expect(file._data).toBe('ParseA==');
});
it('can extract data type from base64 with a complex mime type', () => {
const file = new ParseFile('parse.kml', {
base64: 'data:application/vnd.google-earth.kml+xml;base64,ParseA==',
});
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('application/vnd.google-earth.kml+xml');
expect(file._data).toBe('ParseA==');
});
it('can extract data type from base64 with a charset param', () => {
const file = new ParseFile('parse.kml', {
base64: 'data:application/vnd.3gpp.pic-bw-var;charset=utf-8;base64,ParseA==',
});
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('application/vnd.3gpp.pic-bw-var');
expect(file._data).toBe('ParseA==');
});
it('can create files with byte arrays', () => {
const file = new ParseFile('parse.txt', [61, 170, 236, 120]);
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('');
expect(file._data).toBe('ParseA==');
});
it('can create files with all types of characters', () => {
const file = new ParseFile('parse.txt', [11, 239, 191, 215, 80, 52]);
expect(file._source.base64).toBe('C++/11A0');
expect(file._source.type).toBe('');
expect(file._data).toBe('C++/11A0');
});
it('can create an empty file', () => {
const file = new ParseFile('parse.txt');
expect(file.name()).toBe('parse.txt');
expect(file.url()).toBe(undefined);
});
it('throws when creating a file with invalid data', () => {
expect(function () {
new ParseFile('parse.txt', 12);
}).toThrow('Cannot create a Parse.File with that data.');
expect(function () {
new ParseFile('parse.txt', null);
}).toThrow('Cannot create a Parse.File with that data.');
expect(function () {
new ParseFile('parse.txt', 'string');
}).toThrow('Cannot create a Parse.File with that data.');
});
it('throws with invalid base64', () => {
expect(function () {
b64Digit(65);
}).toThrow('Tried to encode large digit 65 in base64.');
});
it('returns secure url when specified', () => {
const file = new ParseFile('parse.txt', { base64: 'ParseA==' });
return file.save().then(function (result) {
expect(result).toBe(file);
expect(result.url({ forceSecure: true })).toBe('https://files.parsetfss.com/a/parse.txt');
});
});
it('returns undefined when there is no url', () => {
const file = new ParseFile('parse.txt', { base64: 'ParseA==' });
expect(file.url({ forceSecure: true })).toBeUndefined();
});
it('updates fields when saved', () => {
const file = new ParseFile('parse.txt', { base64: 'ParseA==' });
expect(file.name()).toBe('parse.txt');
expect(file.url()).toBe(undefined);
return file.save().then(function (result) {
expect(result).toBe(file);
expect(result.name()).toBe('parse.txt');
expect(result.url()).toBe('http://files.parsetfss.com/a/parse.txt');
});
});
it('updates fields when saved with uri', () => {
const file = new ParseFile('parse.png', {
uri: 'https://example.com/image.png',
});
expect(file.name()).toBe('parse.png');
expect(file.url()).toBe(undefined);
return file.save().then(function (result) {
expect(result).toBe(file);
expect(result.name()).toBe('parse.png');
expect(result.url()).toBe('http://files.parsetfss.com/a/parse.png');
});
});
it('generates a JSON representation', () => {
const file = new ParseFile('parse.txt', { base64: 'ParseA==' });
return file.save().then(function (result) {
expect(result.toJSON()).toEqual({
__type: 'File',
name: 'parse.txt',
url: 'http://files.parsetfss.com/a/parse.txt',
});
});
});
it('can construct a file from a JSON object', () => {
const f = ParseFile.fromJSON({
__type: 'File',
name: 'parse.txt',
url: 'http://files.parsetfss.com/a/parse.txt',
});
expect(f).toBeTruthy();
expect(f.name()).toBe('parse.txt');
expect(f.url()).toBe('http://files.parsetfss.com/a/parse.txt');
expect(ParseFile.fromJSON.bind(null, {})).toThrow('JSON object does not represent a ParseFile');
});
it('can test equality against another ParseFile', () => {
let a = new ParseFile('parse.txt', [61, 170, 236, 120]);
let b = new ParseFile('parse.txt', [61, 170, 236, 120]);
expect(a.equals(a)).toBe(true);
// unsaved files are never equal
expect(a.equals(b)).toBe(false);
expect(b.equals(a)).toBe(false);
a = ParseFile.fromJSON({
__type: 'File',
name: 'parse.txt',
url: 'http://files.parsetfss.com/a/parse.txt',
});
b = ParseFile.fromJSON({
__type: 'File',
name: 'parse.txt',
url: 'http://files.parsetfss.com/a/parse.txt',
});
expect(a.equals(b)).toBe(true);
expect(b.equals(a)).toBe(true);
b = ParseFile.fromJSON({
__type: 'File',
name: 'parse.txt',
url: 'http://files.parsetfss.com/b/parse.txt',
});
expect(a.equals(b)).toBe(false);
expect(b.equals(a)).toBe(false);
});
it('reports progress during save when source is a File', () => {
const file = new ParseFile('progress.txt', new File(['Parse'], 'progress.txt'));
const options = {
progress: function () {},
};
jest.spyOn(options, 'progress');
return file.save(options).then(function (f) {
expect(options.progress).toHaveBeenCalledWith(0.5, 5, 10, {
type: 'upload',
});
expect(f).toBe(file);
expect(f.name()).toBe('progress.txt');
expect(f.url()).toBe('http://files.parsetfss.com/a/progress.txt');
});
});
it('can cancel file upload', () => {
const mockRequestTask = {
abort: () => {},
};
CoreManager.setFileController({
saveFile: function (name, payload, options) {
options.requestTask(mockRequestTask);
return Promise.resolve({});
},
saveBase64: () => {},
download: () => {},
});
const file = new ParseFile('progress.txt', new File(['Parse'], 'progress.txt'));
jest.spyOn(mockRequestTask, 'abort');
file.cancel();
expect(mockRequestTask.abort).toHaveBeenCalledTimes(0);
file.save();
expect(file._requestTask).toEqual(mockRequestTask);
file.cancel();
expect(mockRequestTask.abort).toHaveBeenCalledTimes(1);
});
it('should save file with metadata and tag options', async () => {
const fileController = {
saveFile: jest.fn().mockResolvedValue({}),
saveBase64: () => {},
download: () => {},
};
CoreManager.setFileController(fileController);
const file = new ParseFile('donald_duck.txt', new File(['Parse'], 'donald_duck.txt'));
file.addMetadata('foo', 'bar');
file.addTag('bar', 'foo');
await file.save();
expect(fileController.saveFile).toHaveBeenCalledWith(
'donald_duck.txt',
{
file: expect.any(File),
format: 'file',
type: '',
},
{
metadata: { foo: 'bar' },
tags: { bar: 'foo' },
requestTask: expect.any(Function),
}
);
});
it('should create new ParseFile with metadata and tags', () => {
const metadata = { foo: 'bar' };
const tags = { bar: 'foo' };
const file = new ParseFile('parse.txt', [61, 170, 236, 120], '', metadata, tags);
expect(file._source.base64).toBe('ParseA==');
expect(file._source.type).toBe('');
expect(file._data).toBe('ParseA==');
expect(file.metadata()).toBe(metadata);
expect(file.tags()).toBe(tags);
});
it('should set metadata', () => {
const file = new ParseFile('parse.txt', [61, 170, 236, 120]);
file.setMetadata({ foo: 'bar' });
expect(file.metadata()).toEqual({ foo: 'bar' });
});
it('should set metadata key', () => {
const file = new ParseFile('parse.txt', [61, 170, 236, 120]);
file.addMetadata('foo', 'bar');
expect(file.metadata()).toEqual({ foo: 'bar' });
});
it('should not set metadata if key is not a string', () => {
const file = new ParseFile('parse.txt', [61, 170, 236, 120]);
file.addMetadata(10, '');
expect(file.metadata()).toEqual({});
});
it('should set tags', () => {
const file = new ParseFile('parse.txt', [61, 170, 236, 120]);
file.setTags({ foo: 'bar' });
expect(file.tags()).toEqual({ foo: 'bar' });
});
it('should set tag key', () => {
const file = new ParseFile('parse.txt', [61, 170, 236, 120]);
file.addTag('foo', 'bar');
expect(file.tags()).toEqual({ foo: 'bar' });
});
it('should not set tag if key is not a string', () => {
const file = new ParseFile('parse.txt', [61, 170, 236, 120]);
file.addTag(10, 'bar');
expect(file.tags()).toEqual({});
});
});
describe('FileController', () => {
beforeEach(() => {
CoreManager.setFileController(defaultController);
const request = function (method, path) {
const name = path.substr(path.indexOf('/') + 1);
return Promise.resolve({
name: name,
url: 'https://files.parsetfss.com/a/' + name,
});
};
const ajax = function (method, path) {
const name = path.substr(path.indexOf('/') + 1);
return Promise.resolve({
response: {
name: name,
url: 'https://files.parsetfss.com/a/' + name,
},
});
};
CoreManager.setRESTController({ request: request, ajax: ajax });
});
it('saves files created with bytes', () => {
const file = new ParseFile('parse.txt', [61, 170, 236, 120]);
return file.save().then(function (f) {
expect(f).toBe(file);
expect(f.name()).toBe('parse.txt');
expect(f.url()).toBe('https://files.parsetfss.com/a/parse.txt');
});
});
it('saves files via ajax', () => {
const blob = new Blob([61, 170, 236, 120]);
const file = new ParseFile('parse.txt', blob);
file._source.format = 'file';
return file.save().then(function (f) {
expect(f).toBe(file);
expect(f.name()).toBe('parse.txt');
expect(f.url()).toBe('https://files.parsetfss.com/a/parse.txt');
});
});
it('saveUri with uri type', async () => {
const file = new ParseFile('parse.png', {
uri: 'https://example.com/image.png',
});
const spy = jest.spyOn(defaultController, 'download').mockImplementationOnce(() => {
return Promise.resolve({
base64: 'ParseA==',
contentType: 'image/png',
});
});
const spy2 = jest.spyOn(defaultController, 'saveBase64');
await file.save();
expect(defaultController.download).toHaveBeenCalledTimes(1);
expect(defaultController.saveBase64).toHaveBeenCalledTimes(1);
expect(defaultController.saveBase64.mock.calls[0][0]).toEqual('parse.png');
expect(defaultController.saveBase64.mock.calls[0][1]).toEqual({
format: 'base64',
base64: 'ParseA==',
type: 'image/png',
});
spy.mockRestore();
spy2.mockRestore();
});
it('save with uri download abort', async () => {
const file = new ParseFile('parse.png', {
uri: 'https://example.com/image.png',
});
const spy = jest.spyOn(defaultController, 'download').mockImplementationOnce(() => {
return Promise.resolve({});
});
const spy2 = jest.spyOn(defaultController, 'saveBase64');
await file.save();
expect(defaultController.download).toHaveBeenCalledTimes(1);
expect(defaultController.saveBase64).toHaveBeenCalledTimes(0);
spy.mockRestore();
spy2.mockRestore();
});
it('download with base64 http', async () => {
defaultController._setXHR(null);
const mockResponse = Object.create(EventEmitter.prototype);
EventEmitter.call(mockResponse);
mockResponse.setEncoding = function () {};
mockResponse.headers = {
'content-type': 'image/png',
};
const spy = jest.spyOn(mockHttp, 'get').mockImplementationOnce((uri, cb) => {
cb(mockResponse);
mockResponse.emit('data', 'base64String');
mockResponse.emit('end');
return {
on: function () {},
};
});
const data = await defaultController.download('http://example.com/image.png');
expect(data.base64).toBe('base64String');
expect(data.contentType).toBe('image/png');
expect(mockHttp.get).toHaveBeenCalledTimes(1);
expect(mockHttps.get).toHaveBeenCalledTimes(0);
spy.mockRestore();
});
it('download with base64 http abort', async () => {
defaultController._setXHR(null);
const mockRequest = Object.create(EventEmitter.prototype);
const mockResponse = Object.create(EventEmitter.prototype);
EventEmitter.call(mockRequest);
EventEmitter.call(mockResponse);
mockResponse.setEncoding = function () {};
mockResponse.headers = {
'content-type': 'image/png',
};
const spy = jest.spyOn(mockHttp, 'get').mockImplementationOnce((uri, cb) => {
cb(mockResponse);
return mockRequest;
});
const options = {
requestTask: () => {},
};
defaultController.download('http://example.com/image.png', options).then(data => {
expect(data).toEqual({});
});
mockRequest.emit('abort');
spy.mockRestore();
});
it('download with base64 https', async () => {
defaultController._setXHR(null);
const mockResponse = Object.create(EventEmitter.prototype);
EventEmitter.call(mockResponse);
mockResponse.setEncoding = function () {};
mockResponse.headers = {
'content-type': 'image/png',
};
const spy = jest.spyOn(mockHttps, 'get').mockImplementationOnce((uri, cb) => {
cb(mockResponse);
mockResponse.emit('data', 'base64String');
mockResponse.emit('end');
return {
on: function () {},
};
});
const data = await defaultController.download('https://example.com/image.png');
expect(data.base64).toBe('base64String');
expect(data.contentType).toBe('image/png');
expect(mockHttp.get).toHaveBeenCalledTimes(0);
expect(mockHttps.get).toHaveBeenCalledTimes(1);
spy.mockRestore();
});
it('download with ajax', async () => {
const mockXHR = function () {
return {
DONE: 4,
open: jest.fn(),
send: jest.fn().mockImplementation(function () {
this.response = [61, 170, 236, 120];
this.readyState = 2;
this.onreadystatechange();
this.readyState = 4;
this.onreadystatechange();
}),
getResponseHeader: function () {
return 'image/png';
},
};
};
defaultController._setXHR(mockXHR);
const options = {
requestTask: () => {},
};
const data = await defaultController.download('https://example.com/image.png', options);
expect(data.base64).toBe('ParseA==');
expect(data.contentType).toBe('image/png');
});
it('download with ajax no response', async () => {
const mockXHR = function () {
return {
DONE: 4,
open: jest.fn(),
send: jest.fn().mockImplementation(function () {
this.response = undefined;
this.readyState = 2;
this.onreadystatechange();
this.readyState = 4;
this.onreadystatechange();
}),
getResponseHeader: function () {
return 'image/png';
},
};
};
defaultController._setXHR(mockXHR);
const options = {
requestTask: () => {},
};
const data = await defaultController.download('https://example.com/image.png', options);
expect(data).toEqual({});
});
it('download with ajax abort', async () => {
const mockXHR = function () {
return {
open: jest.fn(),
send: jest.fn().mockImplementation(function () {
this.response = [61, 170, 236, 120];
this.readyState = 2;
this.onreadystatechange();
}),
getResponseHeader: function () {
return 'image/png';
},
abort: function () {
this.status = 0;
this.response = undefined;
this.readyState = 4;
this.onreadystatechange();
},
};
};
defaultController._setXHR(mockXHR);
let _requestTask;
const options = {
requestTask: task => (_requestTask = task),
};
defaultController.download('https://example.com/image.png', options).then(data => {
expect(data).toEqual({});
});
_requestTask.abort();
});
it('download with ajax error', async () => {
const mockXHR = function () {
return {
open: jest.fn(),
send: jest.fn().mockImplementation(function () {
this.onerror('error thrown');
}),
};
};
defaultController._setXHR(mockXHR);
const options = {
requestTask: () => {},
};
try {
await defaultController.download('https://example.com/image.png', options);
} catch (e) {
expect(e).toBe('error thrown');
}
});
it('download with xmlhttprequest unsupported', async () => {
defaultController._setXHR(null);
process.env.PARSE_BUILD = 'browser';
try {
await defaultController.download('https://example.com/image.png');
} catch (e) {
expect(e).toBe('Cannot make a request: No definition of XMLHttpRequest was found.');
}
});
it('getData', async () => {
const file = new ParseFile('parse.png', [61, 170, 236, 120]);
const data = await file.getData();
expect(data).toBe('ParseA==');
});
it('getData unsaved file', async () => {
const file = new ParseFile('parse.png');
try {
await file.getData();
} catch (e) {
expect(e.message).toBe('Cannot retrieve data for unsaved ParseFile.');
}
});
it('getData via download', async () => {
const file = new ParseFile('parse.txt', { base64: 'ParseA==' });
file._data = null;
const result = await file.save();
const spy = jest.spyOn(defaultController, 'download').mockImplementationOnce((uri, options) => {
options.requestTask(null);
return Promise.resolve({
base64: 'ParseA==',
contentType: 'image/png',
});
});
const data = await result.getData();
expect(defaultController.download).toHaveBeenCalledTimes(1);
expect(data).toBe('ParseA==');
spy.mockRestore();
});
it('saves files via ajax with sessionToken option', () => {
const request = function (method, path) {
const name = path.substr(path.indexOf('/') + 1);
return Promise.resolve({
name: name,
url: 'https://files.parsetfss.com/a/' + name,
});
};
const ajax = function (method, path, data, headers) {
expect(headers['X-Parse-Session-Token']).toBe('testing_sessionToken');
const name = path.substr(path.indexOf('/') + 1);
return Promise.resolve({
response: {
name: name,
url: 'https://files.parsetfss.com/a/' + name,
},
});
};
CoreManager.setRESTController({ request, ajax });
const blob = new Blob([61, 170, 236, 120]);
const file = new ParseFile('parse.txt', blob);
file._source.format = 'file';
return file.save({ sessionToken: 'testing_sessionToken' }).then(function (f) {
expect(f).toBe(file);
expect(f.name()).toBe('parse.txt');
expect(f.url()).toBe('https://files.parsetfss.com/a/parse.txt');
});
});
it('saves files via ajax currentUser sessionToken', () => {
CoreManager.set('UserController', {
currentUserAsync() {
return Promise.resolve({
getSessionToken() {
return 'currentUserToken';
},
});
},
});
const request = function (method, path) {
const name = path.substr(path.indexOf('/') + 1);
return Promise.resolve({
name: name,
url: 'https://files.parsetfss.com/a/' + name,
});
};
const ajax = function (method, path, data, headers) {
expect(headers['X-Parse-Session-Token']).toBe('currentUserToken');
const name = path.substr(path.indexOf('/') + 1);
return Promise.resolve({
response: {
name: name,
url: 'https://files.parsetfss.com/a/' + name,
},
});
};
CoreManager.setRESTController({ request, ajax });
const blob = new Blob([61, 170, 236, 120]);
const file = new ParseFile('parse.txt', blob);
file._source.format = 'file';
return file.save().then(function (f) {
expect(f).toBe(file);
expect(f.name()).toBe('parse.txt');
expect(f.url()).toBe('https://files.parsetfss.com/a/parse.txt');
});
});
it('should save file using saveFile with metadata and tags', async () => {
CoreManager.set('UserController', {
currentUserAsync() {
return Promise.resolve({
getSessionToken() {
return 'currentUserToken';
},
});
},
});
const request = jest.fn((method, path) => {
const name = path.substr(path.indexOf('/') + 1);
return Promise.resolve({
name: name,
url: 'https://files.parsetfss.com/a/' + name,
});
});
const ajax = function (method, path, data, headers, options) {
expect(options.sessionToken).toBe('currentUserToken');
const name = path.substr(path.indexOf('/') + 1);
return Promise.resolve({
response: {
name: name,
url: 'https://files.parsetfss.com/a/' + name,
},
});
};
CoreManager.setRESTController({ request, ajax });
const blob = new Blob([61, 170, 236, 120]);
const file = new ParseFile('parse.txt', blob);
file._source.format = 'file';
file.addMetadata('foo', 'bar');
file.addTag('bar', 'foo');
const f = await file.save();
expect(f).toBe(file);
expect(f.name()).toBe('parse.txt');
expect(f.url()).toBe('https://files.parsetfss.com/a/parse.txt');
expect(request).toHaveBeenCalledWith(
'POST',
'files/parse.txt',
{
base64: 'NjExNzAyMzYxMjA=',
fileData: {
metadata: {
foo: 'bar',
},
tags: {
bar: 'foo',
},
},
},
{ requestTask: expect.any(Function) }
);
});
it('saves files via object saveAll options', async () => {
const ajax = async () => {};
const request = jest.fn(async (method, path, data, options) => {
if (path.indexOf('files/') === 0) {
expect(options.sessionToken).toBe('testToken');
return {
name: 'parse.txt',
url: 'http://files.parsetfss.com/a/parse.txt',
};
}
return [{ success: { objectId: 'child' } }];
});
CoreManager.setRESTController({ ajax, request });
CoreManager.setLocalDatastore(mockLocalDatastore);
const blob = new Blob([61, 170, 236, 120]);
const file = new ParseFile('parse.txt', blob);
file._source.format = 'file';
const object = ParseObject.fromJSON({ className: 'TestObject' });
object.set('file', file);
await ParseObject.saveAll([object], { sessionToken: 'testToken' });
expect(request).toHaveBeenCalled();
});
it('should throw error if file deleted without name', async () => {
expect.assertions(1);
const file = new ParseFile('', [1, 2, 3]);
try {
await file.destroy();
} catch (e) {
expect(e.code).toBe(ParseError.FILE_DELETE_UNNAMED_ERROR);
}
});
it('should delete file with masterKey', async () => {
const file = new ParseFile('filename', [1, 2, 3]);
const ajax = jest.fn().mockResolvedValueOnce({ foo: 'bar' });
CoreManager.setRESTController({ ajax, request: () => {} });
CoreManager.set('MASTER_KEY', 'masterKey');
const result = await file.destroy({ useMasterKey: true });
expect(result).toEqual(file);
expect(ajax).toHaveBeenCalledWith('DELETE', 'https://api.parse.com/1/files/filename', '', {
'X-Parse-Application-ID': null,
'X-Parse-Master-Key': 'masterKey',
});
CoreManager.set('MASTER_KEY', null);
});
it('should delete file', async () => {
const file = new ParseFile('filename', [1, 2, 3]);
const ajax = jest.fn().mockResolvedValueOnce({ foo: 'bar' });
CoreManager.setRESTController({ ajax, request: () => {} });
CoreManager.set('MASTER_KEY', 'masterKey');
const result = await file.destroy({ useMasterKey: false });
expect(result).toEqual(file);
expect(ajax).toHaveBeenCalledWith('DELETE', 'https://api.parse.com/1/files/filename', '', {
'X-Parse-Application-ID': null,
});
CoreManager.set('MASTER_KEY', null);
});
it('should handle delete file error', async () => {
const file = new ParseFile('filename', [1, 2, 3]);
const ajax = jest
.fn()
.mockResolvedValueOnce(Promise.reject(new ParseError(403, 'Cannot delete file.')));
const handleError = jest.fn();
CoreManager.setRESTController({ ajax, request: () => {}, handleError });
const result = await file.destroy();
expect(result).toEqual(file);
expect(ajax).toHaveBeenCalledWith('DELETE', 'https://api.parse.com/1/files/filename', '', {
'X-Parse-Application-ID': null,
'X-Parse-Master-Key': null,
});
expect(handleError).toHaveBeenCalled();
});
it('should handle delete file error invalid server response', async () => {
const file = new ParseFile('filename', [1, 2, 3]);
const response = null;
const ajax = jest.fn().mockResolvedValueOnce(Promise.reject(response));
const handleError = jest.fn();
CoreManager.setRESTController({ ajax, request: () => {}, handleError });
const result = await file.destroy();
expect(result).toEqual(file);
expect(ajax).toHaveBeenCalledWith('DELETE', 'https://api.parse.com/1/files/filename', '', {
'X-Parse-Application-ID': null,
'X-Parse-Master-Key': null,
});
expect(handleError).not.toHaveBeenCalled();
});
it('controller saveFile format errors', async () => {
try {
await defaultController.saveFile('parse.txt', { format: 'base64' });
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe('saveFile can only be used with File-type sources.');
}
});
it('controller saveBase64 format errors', async () => {
try {
await defaultController.saveBase64('parse.txt', { format: 'file' });
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe('saveBase64 can only be used with Base64-type sources.');
}
});
it('controller saveFile file reader errors', async () => {
const fileReader = global.FileReader;
class FileReader {
readAsDataURL() {
this.onerror('Could not load file.');
}
}
global.FileReader = FileReader;
try {
await defaultController.saveFile('parse.txt', { format: 'file' });
expect(true).toBe(false);
} catch (e) {
expect(e).toBe('Could not load file.');
}
global.FileReader = fileReader;
});
it('can save unsaved Parse.File property when localDataStore is enabled.', async () => {
mockLocalDatastore.isEnabled = true;
const obj = new ParseObject('Item');
const aFile = new ParseFile('myFileName', [0, 0, 0, 0, 2, 3, 4, 5]);
obj.set('myName', 'helloworld');
obj.set('myFile', aFile);
let error = undefined;
try {
await obj.save();
} catch (e) {
error = e;
}
expect(error).toBeUndefined();
expect(obj.get('myFile').name()).toBe('myFileName');
});
});