forked from ludbek/powerform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.test.js
896 lines (769 loc) · 22.4 KB
/
index.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
const {Form, Field, ValidationError} = require('./index.js')
var noop = () => {}
class BaseField extends Field {
validate(value, all) {
const fieldName = this.fieldName.charAt(0).toUpperCase() +
this.fieldName.slice(1)
if(!value) throw new ValidationError(`"${fieldName}" is required.`)
}
}
class UsernameField extends BaseField {}
class NameField extends BaseField {
modify(value) {
if (!value) return undefined
return value.replace(/(?:^|\s)\S/g, s => s.toUpperCase())
}
}
class PasswordField extends BaseField {
decorate(currentValue, prevValue) {
return "********"
}
}
class ConfirmPasswordField extends BaseField {
validate(value, all, fieldName) {
if (value !== all[this.config.field]) {
throw new ValidationError('Passwords do not match.')
}
}
}
class SignupForm extends Form {
username = UsernameField.new()
name = NameField.new()
password = PasswordField.new()
confirmPassword = ConfirmPasswordField.new({field: 'password'})
}
describe("Field.new()", () => {
it("returns field instance", () => {
let field = Field.new()
expect(field instanceof Field).toEqual(true)
})
})
describe("Field.constructor()", () => {
it("sets default value", () => {
const config = {
default: 'apple'
}
let field = Field.new(config)
expect(field.getData()).toEqual(config.default)
})
it("skips data change trigger while setting default value", () => {
const config = {
default: 'apple',
onChange: jest.fn()
}
let field = Field.new(config)
expect(field.getData()).toEqual(config.default)
expect(config.onChange.mock.calls.length).toEqual(0)
})
it("clones default value", () => {
const value = {}
let field = Field.new()
expect(field.getData()).not.toBe(value)
})
it("won't mark field as dirty", () => {
const config = {
default: 'apple'
}
let field = Field.new(config)
expect(field.isDirty()).toEqual(false)
})
})
describe("Field.setData", () => {
it("clones and sets current value", () => {
const value = {fruit: 'apple'}
let field = Field.new()
field.setData(value)
const got = field.getData()
expect(got).toEqual(value)
expect(got).not.toBe(value)
})
it('calls modifies and sets value returned by it', () => {
let nVal, pVal
class AField extends Field {
modify (newVal, preVal) {
nVal = newVal
pVal = preVal
return newVal.replace(
/(?:^|\s)\S/g,
function(s) {
return s.toUpperCase()
})
}
}
const field = AField.new()
field.setData('red')
field.setData('red apple')
expect(field.getData()).toEqual('Red Apple')
expect(nVal).toEqual('red apple')
expect(pVal).toEqual('Red')
})
it("sets previous value", () => {
const field = Field.new()
field.setData('apple')
expect(field.previousValue).toEqual(undefined)
field.setData('banana')
expect(field.previousValue).toEqual('apple')
})
it('calls onChange callback if exists', () => {
const spy = jest.fn()
const config = {
onChange: spy
}
const field = Field.new(config)
const value = 'apple'
field.setData(value)
expect(spy.mock.calls[0][0]).toEqual(value)
expect(spy.mock.calls[0][1]).toBe(field)
})
it("won't call onChange if value has not changed", () => {
const spy = jest.fn()
const config = {
onChange: spy
}
const field = Field.new(config)
const value = 'apple'
field.setData(value)
expect(spy.mock.calls.length).toEqual(1)
field.setData(value)
expect(spy.mock.calls.length).toEqual(1)
})
it('supports debounce', async () => {
const interval = 1000
let check = false;
let field = Field.new({
debounce: interval,
onChange: value => check = true
})
field.setData('ap')
expect(field.getData()).toEqual('ap')
expect(check).toEqual(false)
await new Promise(r => setTimeout(r, 500))
field.setData('apple')
expect(field.getData()).toEqual('apple')
expect(check).toEqual(false)
await new Promise(r => setTimeout(r, 500))
expect(check).toEqual(false)
await new Promise(r => setTimeout(r, 500))
expect(check).toEqual(true)
})
it("won't call onChange callback if 'skipTrigger' is true", () => {
const spy = jest.fn()
const config = {
onChange: spy
}
const field = Field.new(config)
const value = 'apple'
field.setData(value, true)
expect(spy.mock.calls.length).toEqual(0)
})
})
describe("Field.getData()", () => {
it("clones and returns current value", () => {
const value = {fruit: 'apple'}
let field = Field.new()
field.setData(value)
const got = field.getData()
expect(got).toEqual(value)
expect(got).not.toBe(value)
})
})
describe("Field.getCleanData", () => {
class AField extends Field {
clean(value) {
return value.toUpperCase(value)
}
}
it("returns data processed by Field.clean()", () => {
const f = AField.new({default: "apple"})
expect(f.getData()).toEqual("apple")
expect(f.getCleanData()).toEqual("APPLE")
})
})
describe('Field.isValid()', () => {
class AField extends Field {
validate(value) {
if (!value) {
throw new ValidationError('This field is required.')
}
}
}
it('returns true on positive validation', () => {
let field = AField.new()
field.setData('apple')
expect(field.isValid()).toEqual(true)
})
it('returns false on negative validation', () => {
let field = AField.new()
field.setData(undefined)
expect(field.isValid()).toEqual(false)
})
it('sets error', () => {
let field = AField.new()
field.setData(undefined)
expect(field.isValid()).toEqual(false)
expect(field.getError()).toMatchSnapshot()
})
it('wont set error if true is passed', () => {
let field = AField.new()
field.setData(undefined)
expect(field.isValid(true)).toEqual(false)
expect(field.getError()).toEqual(undefined)
})
it('can validate in relation to other form fields if exists', () => {
class AForm extends Form {
password = PasswordField.new()
confirmPassword = ConfirmPasswordField.new()
}
const f = AForm.new()
f.password.setData("apple")
f.confirmPassword.setData("banana")
expect(f.confirmPassword.isValid()).toEqual(false)
expect(f.confirmPassword.getError()).toEqual("Passwords do not match.")
})
it("won't trigger onError callback if 'skipAttachError' is true", () => {
let config = {
onError: jest.fn()
}
class AField extends Field {
validate(value, allValues) {
if(!value) {
throw new ValidationError("This field is required.")
}
}
}
let f = AField.new(config)
expect(f.isValid(true)).toEqual(false)
expect(config.onError.mock.calls.length).toEqual(0)
})
})
describe('Field.setError()', () => {
it('sets error', () => {
const field = Field.new()
const errMsg = 'Nice error !!!'
field.setError(errMsg)
expect(field.getError()).toEqual(errMsg)
})
it('calls onError callback if exists', () => {
const spy = jest.fn()
const config = {
onError: spy
}
const field = Field.new(config)
const errMsg = 'Nice error !!!'
field.setError(errMsg)
expect(spy.mock.calls.length).toEqual(1)
expect(spy.mock.calls[0]).toMatchSnapshot()
})
it("wont call onError callback if 'skipError' is true", () => {
const spy = jest.fn()
const config = {
onError: spy
}
const field = Field.new(config)
const errMsg = 'Nice error !!!'
field.setError(errMsg, true)
expect(spy.mock.calls.length).toEqual(0)
})
})
describe('Field.getError()', () => {
it('returns error', () => {
const field = Field.new()
const errMsg = 'Nice error !!!'
field.setError(errMsg)
expect(field.getError()).toEqual(errMsg)
})
})
describe('Field.isDirty()', () => {
it('returns true for dirty field', () => {
const field = Field.new()
field.setData('apple')
expect(field.isDirty()).toEqual(true)
})
it('returns false for non dirty field', () => {
const field = Field.new()
expect(field.isDirty()).toEqual(false)
})
it('returns false for default value', () => {
const config = {
default: 'apple'
}
const field = Field.new(config)
expect(field.isDirty()).toEqual(false)
})
})
describe('Field.makePrestine()', () => {
class AField extends Field {
validate(value) {
if(!value) {
throw new ValidationError('This field is required.')
}
}
}
it('sets previousValue and initialValue to currentValue', () => {
const field = AField.new()
field.setData('apple')
expect(field.previousValue).toEqual(undefined)
field.makePrestine()
expect(field.previousValue).toEqual('apple')
expect(field.initialValue).toEqual('apple')
expect(field.isDirty()).toEqual(false)
})
it("empties error", () => {
const field = AField.new()
field.isValid()
expect(field.getError()).toMatchSnapshot()
field.makePrestine()
expect(field.getError()).toEqual(undefined)
})
})
describe('Field.reset()', () => {
class AField extends Field {
validate(value) {
if(!value) {
throw new ValidationError('This field is required.')
}
}
}
it('sets currentValue and previousValue to initialValue', () => {
const config = {
default: 'apple'
}
const field = AField.new(config)
field.setData('banana')
expect(field.currentValue).toEqual('banana')
field.reset()
expect(field.previousValue).toEqual('apple')
expect(field.currentValue).toEqual('apple')
})
it('calls onChange callback', () => {
const spy = jest.fn()
const config = {
default: 'apple',
onChange: spy
}
const field = AField.new(config)
field.setData('banana')
expect(field.currentValue).toEqual('banana')
field.reset()
expect(spy.mock.calls[1][0]).toEqual('apple')
})
it("empties error", () => {
const field = AField.new()
field.isValid()
expect(field.getError()).toMatchSnapshot()
field.reset()
expect(field.getError()).toEqual(undefined)
})
})
describe('Field.setAndValidate()', () => {
class AField extends Field {
validate(value) {
if(!value) {
throw new ValidationError('This field is required.')
}
}
}
it('sets and validates field', () => {
const config = {
default: 'apple'
}
const field = AField.new(config)
const error = field.setAndValidate(undefined)
expect(field.isValid()).toEqual(false)
expect(error).toMatchSnapshot()
})
})
describe("Form.new", () => {
it("returns form instance", () => {
let form = SignupForm.new()
expect(form instanceof SignupForm).toEqual(true)
expect(form instanceof Form).toEqual(true)
})
it("attaches self to each field", () => {
let form = SignupForm.new()
expect(form.username.parent).toBe(form)
expect(form.password.parent).toBe(form)
expect(form.confirmPassword.parent).toBe(form)
})
it("attaches field name to each field", () => {
let form = SignupForm.new()
expect(form.username.fieldName).toEqual('username')
expect(form.password.fieldName).toEqual('password')
expect(form.confirmPassword.fieldName).toEqual('confirmPassword')
})
it("sets initial values", () => {
const data = {
username: 'ausername',
name: 'a name'
}
let spy = jest.fn()
let form = SignupForm.new({data: data, onChange: spy})
const expected = {
username: 'ausername',
name: 'A Name',
password: undefined,
confirmPassword: undefined
}
expect(form.getData()).toEqual(expected)
expect(spy.mock.calls.length).toEqual(0)
})
it("orders cached fields as per index")
})
describe("Form.isValid", () => {
it("returns true if all the fields are valid", () => {
const form = SignupForm.new()
const data = {
username: 'ausername',
name: 'a name',
password: 'apassword',
confirmPassword: 'apassword'
}
form.setData(data)
expect(form.isValid()).toEqual(true)
})
it("returns false if any of the field is invalid", () => {
const form = SignupForm.new()
const data = {
username: 'ausername',
name: 'a name',
password: 'apassword',
confirmPassword: undefined
}
form.setData(data)
expect(form.isValid()).toEqual(false)
})
it("sets error", () => {
const form = SignupForm.new()
form.isValid()
expect(form.getError()).toMatchSnapshot()
})
it("won't set error if true passed", () => {
const form = SignupForm.new()
form.isValid(true)
expect(form.getError()).toMatchSnapshot()
})
it("calls onError callback", () => {
const config = {onError: jest.fn()}
const form = SignupForm.new(config)
form.isValid()
expect(config.onError.mock.calls.length).toEqual(1)
expect(config.onError.mock.calls[0]).toMatchSnapshot()
})
it("won't call onError callback if 'skipAttachError' is true", () => {
const config = {onError: jest.fn()}
const form = SignupForm.new(config)
form.isValid(true)
expect(config.onError.mock.calls.length).toEqual(0)
})
it("respects config.stopOnError", () => {
class AForm extends Form {
username = UsernameField.new({index: 1})
name = NameField.new({index: 2})
password = PasswordField.new({index: 3})
}
const aform = AForm.new({stopOnError: true})
aform.username.setData('a username')
expect(aform.isValid()).toEqual(false)
expect(aform.username.getError()).toEqual(undefined)
expect(aform.name.getError()).toEqual('"Name" is required.')
expect(aform.password.getError()).toEqual(undefined)
})
})
describe("Form.setData", () => {
it("sets data of each field", () => {
const form = SignupForm.new()
const data = {
username: 'ausername',
password: 'apassword'
}
form.setData(data)
expect(form.username.getData()).toEqual(data.username)
expect(form.password.getData()).toEqual(data.password)
})
it("wont trigger update event from fields", () => {
const config = {
onChange: jest.fn()
}
const form = SignupForm.new(config)
const data = {
username: 'ausername',
name: 'A Name',
password: 'apassword',
confirmPassword: 'apassword'
}
form.setData(data)
expect(config.onChange.mock.calls.length).toEqual(1)
expect(config.onChange.mock.calls[0][0]).toEqual(data)
})
})
describe("Form.getData", () => {
it("returns clean data from every fields", () => {
class AField extends Field {
clean (value) {
return value.toUpperCase()
}
}
class AForm extends Form {
afield = AField.new()
username = UsernameField.new()
password = PasswordField.new()
}
const form = AForm.new()
form.afield.setData("apple")
form.username.setData("ausername")
const expected = {
username: "ausername",
password: undefined,
afield: "APPLE"
}
expect(form.getData()).toEqual(expected)
})
})
describe("Form.getUpdates", () => {
it("returns key value pair of updated fields and their value", () => {
const form = SignupForm.new()
form.username.setData("ausername")
form.password.setData("apassword")
const expected = {
username: "ausername",
password: "apassword"
}
expect(form.getUpdates()).toEqual(expected)
})
})
describe("Form.setError", () => {
it("sets error on each field", () => {
const form = SignupForm.new()
const errors = {
username: 'a error',
password: 'a error'
}
form.setError(errors)
expect(form.username.getError()).toEqual(errors.username)
expect(form.password.getError()).toEqual(errors.password)
})
it("calls onError callback only once", () => {
const config = {
onError: jest.fn()
}
const form = SignupForm.new(config)
const errors = {
username: 'a error',
password: 'a error'
}
form.setError(errors)
expect(config.onError.mock.calls.length).toEqual(1)
expect(config.onError.mock.calls[0]).toMatchSnapshot()
})
it("stops at first invalid field if 'haltOnError' is true")
})
describe("Form.getError", () => {
it("returns errors from every fields", () => {
const form = SignupForm.new()
form.username.setError("a error")
form.password.setError("a error")
const expected = {
username: "a error",
name: undefined,
password: "a error",
confirmPassword: undefined
}
expect(form.getError()).toEqual(expected)
})
})
describe("Form.isDirty", () => {
it("returns true if any field's data has changed", () => {
const form = SignupForm.new()
form.username.setData('ausername')
expect(form.isDirty()).toEqual(true)
})
it("returns false if non of the field's data has changed", () => {
const form = SignupForm.new()
expect(form.isDirty()).toEqual(false)
})
})
describe("Form.makePrestine", () => {
it("makes all the fields prestine", () => {
const form = SignupForm.new()
const data = {
username: 'ausername',
password: 'apassword',
confirmPassword: 'password confirmation'
}
form.setData(data)
expect(form.isDirty()).toEqual(true)
form.makePrestine()
expect(form.isDirty()).toEqual(false)
})
it("empties all the error fields and calls onError callback only once", () => {
const config = {
onError: jest.fn()
}
const form = SignupForm.new(config)
const data = {
username: 'ausername'
}
form.setData(data)
form.isValid() // first call
expect(form.isDirty()).toEqual(true)
expect(form.getError()).toMatchSnapshot()
form.makePrestine() // second call
expect(form.isDirty()).toEqual(false)
expect(form.getError()).toMatchSnapshot()
expect(form.getData()).toMatchSnapshot()
expect(config.onError.mock.calls.length).toEqual(2)
})
})
describe("Form.reset", () => {
it("resets all the fields and calls onChange callback only once", () => {
const config = {
onChange: jest.fn()
}
const form = SignupForm.new(config)
const data = {
username: 'ausername',
name: 'a name',
password: 'apassword',
confirmPassword: 'password confirmation'
}
form.setData(data) // first trigger
form.reset() // second trigger
const expected = {
username: undefined,
name: undefined,
password: undefined,
confirmPassword: undefined
}
expect(form.getData()).toEqual(expected)
expect(config.onChange.mock.calls.length).toEqual(2)
})
it("resets all the errors and calls onError callback only once", () => {
const config = {
onError: jest.fn()
}
const form = SignupForm.new(config)
form.isValid() // 1st trigger
form.reset() // 2nd triggter
const expected = {
username: undefined,
name: undefined,
password: undefined,
confirmPassword: undefined
}
expect(form.getError()).toEqual(expected)
expect(config.onError.mock.calls.length).toEqual(2)
})
})
describe("Form.triggerOnChange", () => {
it("calls callback with value and form instance", () => {
const config = {
onChange: jest.fn()
}
const form = SignupForm.new(config)
form.setData({username: 'ausername'})
form.triggerOnChange()
expect(config.onChange.mock.calls.length).toEqual(2)
expect(config.onChange.mock.calls[1]).toMatchSnapshot()
})
it("wont call onChange callback if data has not changed")
it("won't call onChange callback if 'getNotified' is false", () => {
const config = {
onChange: jest.fn()
}
const form = SignupForm.new(config)
form.setData({username: 'ausername'})
form.toggleGetNotified()
form.triggerOnChange()
expect(config.onChange.mock.calls.length).toEqual(1)
})
})
describe("Form.triggerOnError", () => {
it("calls callback with value and form instance", () => {
const config = {
onError: jest.fn()
}
const form = SignupForm.new(config)
form.setError({username: 'an error'})
form.triggerOnError()
expect(config.onError.mock.calls.length).toEqual(2)
expect(config.onError.mock.calls[1]).toMatchSnapshot()
})
it("wont call onError callback if errors have not changed")
it("won't call onError callback if 'getNotified' is false", () => {
const config = {
onError: jest.fn()
}
const form = SignupForm.new(config)
form.isValid()
form.toggleGetNotified()
form.triggerOnError()
expect(config.onError.mock.calls.length).toEqual(1)
})
})
describe("Usage", () => {
it('works with normal validation', () => {
const data = {
username: 'a username',
name: 'a name'
}
const form = SignupForm.new({data: data})
var expected = {
username: 'a username',
name: 'A Name',
password: undefined,
confirmPassword: undefined
}
expect(form.getData()).toEqual(expected)
expect(form.isValid()).toEqual(false)
var expected = {
username: undefined,
name: undefined,
password: '"Password" is required.',
confirmPassword: undefined
}
expect(form.getError()).toEqual(expected)
form.setData({password: 'a password', confirmPassword: 'a password'})
expect(form.isValid()).toEqual(true)
})
})
test("example", () => {
class UsernameField extends Field {
validate(value, allValues) {
if(!value) {
throw new ValidationError( "This field is required.")
}
}
}
class PasswordField extends Field {
validate(value, allValues) {
if(value.length < 8) {
throw new ValidationError("This field must be at least 8 characters long.")
}
}
}
class ConfirmPasswordField extends Field {
validate(value, allValues) {
if (value !== allValues[this.config.passwordField]) {
throw new ValidationError("Passwords do not match.")
}
}
}
class SignupForm extends Form {
username = UsernameField.new()
password = PasswordField.new()
confirmPassword = ConfirmPasswordField.new({passwordField: 'password'})
}
const form = SignupForm.new()
// assign values to fields
form.username.setData("ausername")
form.password.setData("apassword")
form.confirmPassword.setData("bpassword")
// per field validation
console.log(form.username.isValid())
console.log(form.password.isValid())
console.log(form.confirmPassword.isValid())
console.log(form.confirmPassword.getError())
// validate all the fields at once
console.log(form.isValid())
console.log(form.getError())
})