-
-
Notifications
You must be signed in to change notification settings - Fork 771
Expand file tree
/
Copy pathexamples.js
More file actions
68 lines (55 loc) · 1.94 KB
/
examples.js
File metadata and controls
68 lines (55 loc) · 1.94 KB
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
'use strict'
const { tspl } = require('@matteo.collina/tspl')
const { createServer } = require('node:http')
const { test, after } = require('node:test')
const { once } = require('node:events')
const examples = require('../docs/examples/request.js')
test('request examples', async (t) => {
t = tspl(t, { plan: 7 })
let lastReq
const exampleServer = createServer({ joinDuplicateHeaders: true }, (req, res) => {
lastReq = req
if (req.method === 'DELETE') {
res.statusCode = 204
return res.end()
} else if (req.method === 'POST') {
res.statusCode = 200
if (req.url === '/json') {
res.setHeader('content-type', 'application/json')
res.end('{"hello":"JSON Response"}')
} else {
res.end('hello=form')
}
} else {
res.statusCode = 200
res.end('hello')
}
})
const errorServer = createServer({ joinDuplicateHeaders: true }, (req, res) => {
lastReq = req
res.statusCode = 400
res.setHeader('content-type', 'application/json')
res.end('{"error":"an error"}')
})
after(() => exampleServer.close())
after(() => errorServer.close())
exampleServer.listen(0)
errorServer.listen(0)
await Promise.all([
once(exampleServer, 'listening'),
once(errorServer, 'listening')
])
await examples.getRequest(exampleServer.address().port)
t.strictEqual(lastReq.method, 'GET')
await examples.postJSONRequest(exampleServer.address().port)
t.strictEqual(lastReq.method, 'POST')
t.strictEqual(lastReq.headers['content-type'], 'application/json')
await examples.postFormRequest(exampleServer.address().port)
t.strictEqual(lastReq.method, 'POST')
t.strictEqual(lastReq.headers['content-type'], 'application/x-www-form-urlencoded')
await examples.deleteRequest(exampleServer.address().port)
t.strictEqual(lastReq.method, 'DELETE')
await examples.deleteRequest(errorServer.address().port)
t.strictEqual(lastReq.method, 'DELETE')
await t.completed
})