-
Notifications
You must be signed in to change notification settings - Fork 0
/
Validator.spec.js
355 lines (284 loc) · 10.9 KB
/
Validator.spec.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
'use strict'
const { load } = require('js-yaml')
const { expect } = require('chai')
const { readFileSync } = require('fs')
const { Schema, Validator } = require('src')
const loadSync = (yamlPath) => {
const id = yamlPath.split('.')[0].split('/').reverse()[0]
const source = load(readFileSync(yamlPath))
return new Schema(source, id)
}
const SCHEMAS = [
'examples/Status.yaml',
'examples/Profile.yaml',
'examples/Preferences.yaml',
'examples/FavoriteItem.yaml'
].map(path => loadSync(path))
describe('Validator', () => {
describe('Validator.constructor(schemas)', () => {
it('create validator for schemas', () => {
new Validator(SCHEMAS)
})
it('throws error if no schemas provided', () => {
expect(
() => new Validator()
).to.throw('No schemas provided')
})
it('throws error if referenced schema not found', () => {
const entitySchema = new Schema({ name: { $ref: 'MissingSchema' } }, 'Entity')
expect(
() => new Validator([ ...SCHEMAS, entitySchema ])
).to.throw('Schemas validation failed:')
})
})
describe('.validate(object, schemaId, shouldNullifyEmptyValues = false, shouldCleanupNulls = true)', () => {
it('returns validated, cleaned and normalized object', () => {
const validator = new Validator(SCHEMAS)
const _createdAt = new Date().toISOString()
const input = {
name: 'Oleksandr',
toBeRemoved: null,
contactDetails: {
email: '[email protected]',
toBeRemoved: null,
},
favoriteItems: [
{
id: '1',
name: 'Student Book',
categories: [ 'Education' ],
toBeRemoved: null,
_createdAt
},
],
locations: [{
name: 'Home',
address: {
type: 'Primary',
zip: '03119',
city: 'Kyiv',
addressLine1: 'Melnikova 83-D, 78',
_createdAt
},
_createdAt
}],
preferences: {
height: 180,
isNotificationEnabled: true,
_createdAt
},
status: 'Active',
_createdAt
}
const validInput = validator.validate(input, 'Profile', false, true)
expect(validInput.toBeRemoved).to.not.exist
expect(validInput.contactDetails.toBeRemoved).to.not.exist
expect(validInput.favoriteItems[0].toBeRemoved).to.not.exist
expect(validInput._createdAt).to.not.exist
expect(validInput.preferences._createdAt).to.not.exist
expect(validInput.locations[0]._createdAt).to.not.exist
expect(validInput.locations[0].address._createdAt).to.not.exist
expect(validInput.favoriteItems[0]._createdAt).to.not.exist
expect(validInput.name).to.eql('Oleksandr')
expect(validInput.gender).to.eql('Other')
expect(validInput.status).to.eql('Active')
expect(validInput.locations[0].name).to.eql('Home')
expect(validInput.locations[0].address.country).to.eql('Ukraine')
expect(validInput.locations[0].address.zip).to.eql('03119')
expect(validInput.locations[0].address.city).to.eql('Kyiv')
expect(validInput.locations[0].address.addressLine1).to.eql('Melnikova 83-D, 78',)
expect(validInput.locations[0].address.type).to.eql('Primary')
expect(validInput.favoriteItems[0].id).to.eql('1')
expect(validInput.favoriteItems[0].name).to.eql('Student Book')
expect(validInput.favoriteItems[0].categories).to.deep.eql([ 'Education' ])
expect(validInput.favoriteItems[0].status).to.eql('Pending')
expect(validInput.contactDetails.email).to.eql('[email protected]')
expect(validInput.contactDetails.mobileNumber).to.eql('380504112171')
expect(validInput.preferences.height).to.eql(180)
expect(validInput.preferences.isNotificationEnabled).to.eql(true)
})
it('normalizes object attributes according to property type', () => {
const validator = new Validator(SCHEMAS)
const input = {
name: 'Oleksandr',
contactDetails: {
email: '[email protected]'
},
preferences: {
height: '180',
isNotificationEnabled: 'true'
}
}
let validInput
validInput = validator.validate(input, 'Profile')
expect(validInput.preferences.height).to.eql(180)
expect(validInput.preferences.isNotificationEnabled).to.eql(true)
input.preferences.isNotificationEnabled = '1'
validInput = validator.validate(input, 'Profile')
expect(validInput.preferences.isNotificationEnabled).to.eql(true)
input.preferences.isNotificationEnabled = '0'
validInput = validator.validate(input, 'Profile')
expect(validInput.preferences.isNotificationEnabled).to.eql(false)
input.preferences.isNotificationEnabled = 0
validInput = validator.validate(input, 'Profile')
expect(validInput.preferences.isNotificationEnabled).to.eql(false)
expect(() => {
input.preferences.isNotificationEnabled = 'NaN'
validInput = validator.validate(input, 'Profile')
expect(validInput.preferences.isNotificationEnabled).to.eql('NaN')
}).to.throw('"Profile" validation failed')
expect(() => {
input.preferences.isNotificationEnabled = 0
input.preferences.height = 'NaN'
validInput = validator.validate(input, 'Profile')
expect(validInput.preferences.height).to.eql('NaN')
}).to.throw('"Profile" validation failed')
})
it('throws validation error if cleanup or normalize method failed', () => {
const validator = new Validator(SCHEMAS)
const input = {
name: 'Oleksandr',
contactDetails: {
email: '[email protected]'
},
favoriteItems: 'NOT_ARRAY_BUT_STRING'
}
try {
validator.validate(input, 'Profile')
} catch (validationError) {
const error = validationError.toJSON()
expect(error.object).to.exist
expect(error.code).to.eql('ValidationError')
expect(error.message).to.eql('"Profile" validation failed')
expect(error.schemaId).to.eql('Profile')
const errorMessage = error.validationErrors[0].message
expect(errorMessage).to.eql('Expected type array but found type string')
return
}
throw new Error('Validation error is not thrown')
})
it('throws error if validation failed', () => {
const validator = new Validator(SCHEMAS)
const input = {}
try {
validator.validate(input, 'Profile')
} catch (validationError) {
const error = validationError.toJSON()
expect(error.object).to.exist
expect(error.code).to.eql('ValidationError')
expect(error.message).to.eql('"Profile" validation failed')
expect(error.schemaId).to.eql('Profile')
expect(error.validationErrors).to.have.lengthOf(2)
return
}
throw new Error('Validation error is not thrown')
})
it('throws error if schema not found', () => {
const validator = new Validator(SCHEMAS)
expect(
() => validator.validate({}, 'Account')
).to.throw('Schema "Account" not found')
})
it('throws error if multiple schemas with same id', async () => {
const exampleSchema1 = new Schema({
number: { required: true }
}, 'Example')
const exampleSchema2 = new Schema({
id: {}
}, 'Example')
expect(() => new Validator([ exampleSchema1, exampleSchema2 ]))
.to.throw('Multiple "Example" schemas provided')
})
})
describe('.validate(object, schemaId, shouldNullifyEmptyValues = false)', () => {
it('throws validation error for attributes not matching format or pattern', () => {
const validator = new Validator(SCHEMAS)
const input = {
name: 'Oleksandr',
gender: '',
contactDetails: {
email: '[email protected]',
secondaryEmail: '',
mobileNumber: '',
},
}
expect(
() => validator.validate(input, 'Profile')
).to.throw('"Profile" validation failed')
})
})
describe('.validate(object, schemaId, shouldNullifyEmptyValues = true)', () => {
it('returns input with cleaned up null values for not required attributes', () => {
const validator = new Validator(SCHEMAS)
const input = {
name: 'Oleksandr',
gender: '', // ENUM
contactDetails: {
email: '[email protected]',
mobileNumber: '', // PATTERN
secondaryEmail: '', // FORMAT
},
}
const validInput = validator.validate(input, 'Profile', true)
expect(validInput.gender).to.eql(null)
expect(validInput.contactDetails.mobileNumber).to.eql(null)
expect(validInput.contactDetails.secondaryEmail).to.eql(null)
})
it('throws validation errors for other attributes', () => {
const validator = new Validator(SCHEMAS)
const input = {
name: '', // code: MIN_LENGTH
gender: 'NONE', // code: ENUM_MISMATCH
contactDetails: {
email: '[email protected]',
mobileNumber: 'abc', // code: PATTERN
secondaryEmail: '',
},
preferences: {
age: 'a' // code: INVALID_TYPE
},
}
try {
validator.validate(input, 'Profile', true)
} catch (validationError) {
const error = validationError.toJSON()
expect(error.message).to.eql('"Profile" validation failed')
expect(error.validationErrors).to.have.lengthOf(4)
expect(error.validationErrors[0].code).to.eql('INVALID_TYPE')
expect(error.validationErrors[1].code).to.eql('PATTERN')
expect(error.validationErrors[2].code).to.eql('ENUM_MISMATCH')
expect(error.validationErrors[3].code).to.eql('MIN_LENGTH')
return
}
throw new Error('Validation error is not thrown')
})
})
describe('.normalize(object, schemaId)', () => {
it('returns normalized object clone', () => {
const validator = new Validator(SCHEMAS)
const input = {}
const normalizedInput = validator.normalize(input, 'Profile')
expect(normalizedInput.gender).to.eql('Other')
expect(normalizedInput.status).to.eql('Pending')
})
it('throws error if schema not found', () => {
const validator = new Validator(SCHEMAS)
expect(
() => validator.normalize({}, 'Account')
).to.throw('Schema "Account" not found')
})
})
describe('.schemasMap', () => {
it('returns schemas map', () => {
const validator = new Validator(SCHEMAS)
expect(validator.schemasMap).to.exist
})
})
describe('.getReferenceIds(schemaId)', () => {
it('returns ids of referenced schemas', () => {
const validator = new Validator(SCHEMAS)
const referenceIds = validator.getReferenceIds('Profile')
expect(referenceIds).to.eql([ 'Status', 'FavoriteItem', 'Preferences' ])
})
})
})