/
validateDocument.test.ts
708 lines (667 loc) · 18.2 KB
/
validateDocument.test.ts
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
import type {SanityClient} from '@sanity/client'
import {
Rule,
SchemaType,
SanityDocument,
Schema,
ArraySchemaType,
PortableTextTextBlock,
} from '@sanity/types'
import {createSchema} from '../test/createSchema'
import {createMockSanityClient} from '../test/mocks/mockSanityClient'
import validateDocument, {resolveTypeForArrayItem, validateItem} from './validateDocument'
import {convertToValidationMarker} from './util/convertToValidationMarker'
jest.mock('./util/convertToValidationMarker', () => {
return {
convertToValidationMarker: jest.fn(
jest.requireActual('./util/convertToValidationMarker').convertToValidationMarker
),
}
})
beforeEach(() => {
;(convertToValidationMarker as jest.Mock).mockClear()
})
// mock client
const client = createMockSanityClient() as any as SanityClient
const getClient = (options: {apiVersion: string}) => client
describe('resolveTypeForArrayItem', () => {
const schema: Schema = createSchema({
types: [
{
name: 'foo',
type: 'object',
fields: [{name: 'title', type: 'number'}],
},
{
name: 'bar',
type: 'object',
fields: [{name: 'title', type: 'string'}],
},
],
})
const fooType = schema.get('foo')
const barType = schema.get('bar')
it('finds a matching schema type for an array item value given a list of candidate types', () => {
const resolved = resolveTypeForArrayItem(
{
_type: 'bar',
_key: 'exampleKey',
title: 5,
},
[fooType!, barType!]
)
expect(resolved).toBe(barType)
})
it('assumes the type if there is only one possible candidate', () => {
const resolved = resolveTypeForArrayItem(
{
// notice no _type
_key: 'exampleKey',
title: 5,
},
[fooType!]
)
expect(resolved).toBe(fooType)
})
})
describe('validateDocument', () => {
it('takes in a document + a compiled schema and returns a list of validation markers', async () => {
const schema = createSchema({
types: [
{
name: 'simpleDoc',
type: 'document',
title: 'Simple Document',
fields: [
{
name: 'title',
type: 'string',
validation: (rule: Rule) => rule.required(),
},
],
},
],
})
const document: SanityDocument = {
_id: 'testId',
_createdAt: '2021-08-27T14:48:51.650Z',
_rev: 'exampleRev',
_type: 'simpleDoc',
_updatedAt: '2021-08-27T14:48:51.650Z',
title: null,
}
const result = await validateDocument(getClient, document, schema)
expect(result).toMatchObject([
{
level: 'error',
item: {
message: 'Expected type "String", got "null"',
paths: [],
},
path: ['title'],
},
{
level: 'error',
item: {
message: 'Required',
paths: [],
},
path: ['title'],
},
])
})
})
describe('validateItem', () => {
it("runs nested validation on an undefined value for object types if it's required", async () => {
const validation = (rule: Rule) => [
rule.required().error('This is required!'),
rule.max(160).warning('Too long!'),
]
const schema = createSchema({
types: [
{
name: 'testObj',
type: 'object',
title: 'Test Object',
fields: [
{name: 'registeredString', type: 'registeredString'},
{name: 'inlineString', type: 'string', validation},
{
name: 'registeredObject',
type: 'registeredObjectField',
validation: (rule: Rule) => rule.required(),
},
{
name: 'inlineObject',
type: 'object',
fields: [{name: 'foo', type: 'string', validation}],
validation: (rule: Rule) => rule.required(),
},
{
name: 'notRequiredRegisteredObject',
type: 'registeredObjectField',
},
{
name: 'notRequiredInlineObject',
type: 'object',
fields: [{name: 'foo', type: 'string', validation}],
},
],
},
{name: 'registeredString', title: 'Registered String', type: 'string', validation},
{
title: 'Registered Object Field',
name: 'registeredObjectField',
type: 'object',
fields: [{name: 'foo', type: 'string', validation}],
},
],
})
// ensures there are no schema formatting issues
expect(schema._validation).toHaveLength(0)
await expect(
validateItem({
client,
getClient,
schema,
value: {},
document: undefined,
path: [],
parent: undefined,
type: schema.get('testObj'),
getDocumentExists: undefined,
})
).resolves.toMatchObject([
{
level: 'error',
item: {message: 'This is required!'},
path: ['registeredString'],
},
{
level: 'error',
item: {message: 'This is required!'},
path: ['inlineString'],
},
{
level: 'error',
item: {message: 'Required'},
path: ['registeredObject'],
},
{
level: 'error',
item: {message: 'This is required!'},
path: ['registeredObject', 'foo'],
},
{
level: 'error',
item: {message: 'Required'},
path: ['inlineObject'],
},
{
level: 'error',
item: {message: 'This is required!'},
path: ['inlineObject', 'foo'],
},
])
})
it('runs nested validation for object-level rules set via Rule.fields()', async () => {
const schema = createSchema({
types: [
{
name: 'testObj',
type: 'object',
title: 'Test Object',
fields: [
{name: 'foo', type: 'string'},
{name: 'bar', type: 'string'},
],
validation: (rule: Rule) => [
rule.required(),
rule.fields({
foo: (r) => r.required(),
bar: (r) => r.required(),
}),
],
},
],
})
// ensures there are no schema formatting issues
expect(schema._validation).toHaveLength(0)
await expect(
validateItem({
client,
getClient,
schema,
document: undefined,
parent: undefined,
path: undefined,
type: schema.get('testObj'),
value: {foo: 5},
getDocumentExists: undefined,
})
).resolves.toMatchObject([
{
item: {message: 'Expected type "String", got "Number"'},
level: 'error',
path: ['foo'],
},
{
item: {message: 'Required'},
level: 'error',
path: ['bar'],
},
])
})
// @todo this one fails, needs investigation for what is actually the expected outcome
it.skip('runs nested validation for markDefs', async () => {
const linkValidationSpy = jest.fn(() => true as const)
const internalLinkSpy = jest.fn(() => 'mock invalid response')
const schema = createSchema({
types: [
{
name: 'post',
title: 'Post',
type: 'document',
fields: [
{name: 'title', type: 'string'},
{name: 'body', type: 'string'},
],
},
{
name: 'registeredEditor',
type: 'object',
title: 'Registered Editor',
fields: [
{
name: 'editor',
type: 'array',
of: [
{
type: 'block',
marks: {
annotations: [
{
name: 'exampleAnnotation',
type: 'object',
fields: [{name: 'value', type: 'string'}],
},
],
},
},
],
},
],
},
{
name: 'blockTest',
type: 'document',
title: 'blockTest',
fields: [
{
name: 'content',
title: 'Content',
type: 'array',
of: [
{
type: 'block',
marks: {
annotations: [
{
name: 'link',
type: 'object',
title: 'link',
fields: [{name: 'url', type: 'url'}],
validation: (rule: Rule) => rule.custom(linkValidationSpy),
},
{
name: 'internalLink',
type: 'object',
title: 'Internal link',
fields: [{name: 'reference', type: 'reference', to: [{type: 'post'}]}],
validation: (rule: Rule) => rule.custom(internalLinkSpy),
},
{name: 'nestedEditor', type: 'registeredEditor'},
],
},
},
],
},
],
},
],
})
expect(schema._validation).toHaveLength(0)
const nestedBlock: PortableTextTextBlock = {
_type: 'block',
_key: 'nested-block-key',
children: [
{
_key: 'some-key',
_type: 'span',
text: 'hey',
marks: ['example-annotation-key'],
},
],
markDefs: [
{
_type: 'exampleAnnotation',
_key: 'example-annotation-key',
value: 5,
},
],
style: 'normal',
}
const block: PortableTextTextBlock = {
_key: 'block-key',
_type: 'block',
children: [
{
_key: 'child-0',
_type: 'span',
marks: ['0', '1', '2'],
text: 'hey',
},
],
markDefs: [
{
_key: '0',
_type: 'link',
url: 'https://example.com',
},
{
_key: '1',
_type: 'internalLink',
_ref: 'post-id',
},
{
_key: '2',
_type: 'nestedEditor',
editor: [nestedBlock],
},
],
style: 'normal',
}
const document: SanityDocument = {
_id: 'mock-id',
_type: 'blockTest',
_createdAt: '2021-11-15T21:06:41.812Z',
_rev: 'example-ref',
_updatedAt: '2021-11-15T21:06:41.812Z',
content: [block],
}
const result = await validateItem({
client,
getClient,
schema,
document: document,
parent: undefined,
path: [],
type: schema.get('blockTest'),
value: document,
getDocumentExists: undefined,
})
expect(result).toMatchObject([
{
item: {message: 'mock invalid response', paths: []},
level: 'error',
path: ['content', {_key: 'block-key'}, 'markDefs', {_key: '1'}],
},
// this tests for nested markDef validation
{
item: {
message: 'Expected type "String", got "Number"',
paths: [],
},
level: 'error',
path: [
'content',
{_key: 'block-key'},
'markDefs',
{_key: '2'},
'editor',
{_key: 'nested-block-key'},
'markDefs',
{_key: 'example-annotation-key'},
'value',
],
},
])
expect(linkValidationSpy.mock.calls).toMatchObject([
[
{
_key: '0',
_type: 'link',
url: 'https://example.com',
},
{
document: {_id: 'mock-id'},
parent: {_key: 'block-key'},
path: ['content', {_key: 'block-key'}, 'markDefs', {_key: '0'}],
type: {name: 'link'},
},
],
])
expect(internalLinkSpy.mock.calls).toMatchObject([
[
{
_key: '1',
_ref: 'post-id',
_type: 'internalLink',
},
{
document: {_id: 'mock-id'},
parent: {_key: 'block-key'},
path: ['content', {_key: 'block-key'}, 'markDefs', {_key: '1'}],
type: {name: 'internalLink'},
},
],
])
})
it('resolves an array item type if there is just one type', async () => {
const schema = createSchema({
types: [
{
name: 'values',
title: 'Values',
type: 'array',
// note that there is only one type available
of: [{type: 'arrayItem'}],
validation: (rule: Rule) => rule.required(),
},
{
title: 'Array Item',
name: 'arrayItem',
type: 'object',
fields: [{name: 'title', type: 'string'}],
},
],
})
// ensures there are no schema formatting issues
expect(schema._validation).toHaveLength(0)
const values = [
{
// note how this doesn't have a _type
title: 5,
_key: 'exampleKey',
},
]
await expect(
validateItem({
client,
getClient,
schema,
document: undefined,
parent: undefined,
path: [],
type: schema.get('values'),
value: values,
getDocumentExists: undefined,
})
).resolves.toEqual([
{
level: 'error',
item: {
message: 'Expected type "String", got "Number"',
paths: [],
},
path: [{_key: 'exampleKey'}, 'title'],
},
])
})
it('properly passes the nested value, type, and path to rule.validate', async () => {
const schema: Schema = createSchema({
types: [
{
name: 'root',
type: 'object',
title: 'Root',
fields: [
{
name: 'level1Object',
type: 'object',
validation: (rule: Rule) => rule.custom(() => 'from level 1 object'),
fields: [
{
name: 'level2String',
type: 'string',
validation: (rule: Rule) => rule.custom(() => 'from level 2 via object'),
},
],
},
{
name: 'level1Array',
type: 'array',
validation: (rule: Rule) => rule.custom(() => 'from level 1 array'),
of: [
{
type: 'object',
fields: [
{
name: 'level2Number',
type: 'number',
validation: (rule: Rule) => rule.custom(() => 'from level 2 via array'),
},
],
},
],
},
],
validation: (rule: Rule) => rule.custom(() => 'from root'),
},
],
})
// ensures there are no schema formatting issues
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((schema as any)._validation).toHaveLength(0)
const value = {
level1Object: {level3String: 'a string'},
level1Array: [{level2Number: 5}],
}
const document: SanityDocument = {
value,
_type: 'something',
_createdAt: '2021-09-05T19:28:30.882Z',
_id: 'something.id',
_rev: 'exampleRev',
_updatedAt: '2021-09-05T19:28:30.882Z',
}
const getField = ({in: type, name}: {in: SchemaType; name: string}) => {
const result = 'fields' in type && type.fields.find((f) => f.name === name)?.type
if (!result) throw new Error(`Could not find field \`${name}\` in \`${type.name}\``)
return result
}
const rootType = schema.get('root')
const level1ObjectType = getField({in: rootType!, name: 'level1Object'})
const level2StringType = getField({in: level1ObjectType, name: 'level2String'})
const level1ArrayType = getField({in: rootType!, name: 'level1Array'})
const level2NumberType = getField({
in: (level1ArrayType as ArraySchemaType).of[0],
name: 'level2Number',
})
await expect(
validateItem({
client,
getClient,
schema,
value,
type: rootType,
document,
parent: document,
path: undefined,
getDocumentExists: undefined,
})
).resolves.toMatchObject([
{
item: {message: 'from root'},
path: [],
},
{
item: {message: 'from level 1 object'},
path: ['level1Object'],
},
{
item: {message: 'from level 2 via object'},
path: ['level1Object', 'level2String'],
},
{
item: {message: 'from level 1 array'},
path: ['level1Array'],
},
{
item: {message: 'from level 2 via array'},
path: ['level1Array', 0, 'level2Number'],
},
])
const calls = (convertToValidationMarker as jest.Mock).mock.calls
expect(calls.find((call) => call[0] === 'from root')).toMatchObject([
'from root',
'error',
{
parent: document,
document: document,
path: [],
type: rootType,
},
])
expect(calls.find((call) => call[0] === 'from level 1 object')).toMatchObject([
'from level 1 object',
'error',
{
parent: value,
document: document,
path: ['level1Object'],
type: level1ObjectType,
},
])
expect(calls.find((call) => call[0] === 'from level 2 via object')).toMatchObject([
'from level 2 via object',
'error',
{
parent: value.level1Object,
document: document,
path: ['level1Object', 'level2String'],
type: level2StringType,
},
])
expect(calls.find((call) => call[0] === 'from level 1 array')).toMatchObject([
'from level 1 array',
'error',
{
parent: value,
document: document,
path: ['level1Array'],
type: level1ArrayType,
},
])
expect(calls.find((call) => call[0] === 'from level 2 via array')).toMatchObject([
'from level 2 via array',
'error',
{
parent: value.level1Array[0],
document: document,
path: ['level1Array', 0, 'level2Number'],
type: level2NumberType,
},
])
})
})