/
bodyParser.test.js
96 lines (83 loc) · 2.28 KB
/
bodyParser.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
/**
* Module dependencies.
*/
var connect = require('../')
, assert = require('assert')
, http = require('http');
var app = connect.createServer(
connect.bodyParser(),
function(req, res){
res.writeHead(200);
res.end(JSON.stringify(req.body));
});
module.exports = {
'test x-www-form-urlencoded body': function(){
assert.response(app,
{ url: '/'
, data: 'foo=bar'
, method: 'POST'
, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }},
{ body: '{"foo":"bar"}' });
},
'test PUT x-www-form-urlencoded body': function(){
assert.response(app,
{ url: '/'
, data: 'foo=bar'
, method: 'PUT'
, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }},
{ body: '{"foo":"bar"}' });
},
'test json body': function(){
assert.response(app,
{ url: '/'
, data: '{"foo":"bar"}'
, method: 'PUT'
, headers: { 'Content-Type': 'application/json' }},
{ body: '{"foo":"bar"}' });
},
'test POST with no data': function(){
assert.response(app,
{ url: '/', method: 'POST' },
{ body: '{}' });
},
'test GET with content-type': function(){
assert.response(app,
{ url: '/', headers: { 'Content-Type': 'application/json' }},
{ body: '{}' });
},
'test custom parser': function(){
connect.bodyParser.parse['application/x-awesome'] = function(req, options, fn){
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk; });
req.on('end', function(){
var parts = buf.split('.');
req.body = {};
req.body[parts.shift()] = parts.shift();
fn();
});
};
assert.response(app,
{ url: '/'
, method: 'POST'
, data: 'foo.bar'
, headers: { 'Content-Type': 'application/x-awesome' }},
{ body: '{"foo":"bar"}' });
},
'test mount-safety': function(){
var app = connect(
connect.bodyParser()
, function(req, res){
res.end(req.body.name);
}
);
var app2 = connect(connect.bodyParser());
app2.use('/test', app);
assert.response(app2,
{ url: '/test'
, method: 'POST'
, data: '{"name":"tj"}'
, headers: { 'Content-Type': 'application/json' }},
{ body: 'tj' });
}
};