forked from mochajs/mocha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.meta.2.js
82 lines (70 loc) · 1.68 KB
/
http.meta.2.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
var http = require('http');
var server = http.createServer(function(req, res){
var accept = req.headers.accept || ''
, json = ~accept.indexOf('json');
switch (req.url) {
case '/':
res.end('hello');
break;
case '/users':
if (json) {
res.end('["tobi","loki","jane"]');
} else {
res.end('tobi, loki, jane');
}
break;
}
})
server.listen(8899);
function get(url) {
var fields
, expected
, header = {};
function request(done) {
http.get({ path: url, port: 8899, headers: header }, function(res){
var buf = '';
res.should.have.property('statusCode', 200);
res.setEncoding('utf8');
res.on('data', function(chunk){ buf += chunk });
res.on('end', function(){
buf.should.equal(expected);
done();
});
})
}
return {
set: function(field, val){
header[field] = val;
return this;
},
should: {
respond: function(body){
fields = Object.keys(header).map(function(field){
return field + ': ' + header[field];
}).join(', ');
expected = body;
describe('GET ' + url, function(){
if (fields) {
describe('when given ' + fields, function(){
it('should respond with "' + body + '"', request);
});
} else {
it('should respond with "' + body + '"', request);
}
});
}
}
};
}
describe('http server', function(){
get('/')
.should
.respond('hello')
get('/users')
.should
.respond('tobi, loki, jane')
get('/users')
.set('Accept', 'application/json')
.should
.respond('["tobi","loki","jane"]')
})