-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
http-meta-2.spec.js
96 lines (81 loc) · 1.92 KB
/
http-meta-2.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
'use strict';
var http = require('http');
var PORT = 8899;
var server = http.createServer(function (req, res) {
var accept = req.headers.accept || '';
var 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;
}
});
function get (url) {
var fields;
var expected;
var header = {};
function request (done) {
http.get({ path: url, port: PORT, 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 () {
this.timeout(500);
if (fields) {
describe('when given ' + fields, function () {
it('should respond with "' + body + '"', request);
});
} else {
it('should respond with "' + body + '"', request);
}
});
}
}
};
}
describe('http server', function () {
before(function (done) {
server.listen(PORT, done);
});
beforeEach(function () {
this.timeout(2000);
});
after(function () {
server.close();
});
get('/')
.should
.respond('hello');
get('/users')
.should
.respond('tobi, loki, jane');
get('/users')
.set('Accept', 'application/json')
.should
.respond('["tobi","loki","jane"]');
});