-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrequest_validation_test.js
112 lines (92 loc) · 2.71 KB
/
request_validation_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
var assert = require('assert')
var validator = require('../index')
var email = validator.email
var presence = validator.presence
function fakeRequest() {
return {
params: {},
query: {},
body: {}
}
}
// Used to setup some generic tests
//
// title -> Body, Request or Query validations
// validateFunction -> Function used to validate params: validateBody, validateQuery, validateParams
// property -> which property of the request to use for setting up the params.
// request.body, request.query, request.params
//
function validation(title, validateFunction, property) {
describe(title, function() {
var req
before(function() {
req = fakeRequest()
})
it('runs validations on the request ' + title, function() {
req[property] = {
login: 'nettofarah',
password: 'secret',
email: 'nettofarah@gmail.com'
}
var validation = validateFunction(req, [
presence('login'),
presence('password'),
email('email')
])
assert(validation.valid)
assert(validation.errors.length == 0)
})
describe('failed validations', function() {
var validation
before(function() {
req[property] = {
login: 'nettofarah',
email: 'nettofarahatgmail.com'
}
validation = validateFunction(req, [
presence('login'),
presence('password'),
email('email')
])
})
it('only passes if all validations pass', function() {
assert(validation.valid == false)
})
it('returns all failed validations', function() {
assert(validation.errors.length == 2)
assert(validation.errors[0].field == 'password')
assert(validation.errors[1].field == 'email')
})
it('returns all the error messages', function() {
assert.deepEqual(validation.messages, [
'"password" required',
'"email" should look like an email address'
])
})
})
})
}
validation('Body Validation', validator.validateBody, 'body')
validation('Params Validation', validator.validateParams, 'params')
validation('Query String Validation', validator.validateQuery, 'query')
validation('Headers Validation', validator.validateHeaders, 'headers')
describe('Validate all', function() {
it('validates all properties across body, query and params', function() {
var req = fakeRequest()
req.body = {
password: 'secret'
}
req.query = {
email: 'nettofarah@gmail.com'
}
req.params = {
login: 'nettofarah'
}
var validation = validator.validateAll(req, [
presence('password'),
email('email'),
presence('login')
])
assert(validation.valid)
})
})