blob: 7d82c16d114139605417fd31f53e98dfa1d1062a [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001var testServer = require("test-server")
2var test = require("tape")
3var sendJson = require("send-data/json")
4var after = require("after")
5
6var body = require("../index")
7var jsonBody = require("../json")
8var formBody = require("../form")
9var anyBody = require("../any")
10
11testServer(handleRequest, runTests)
12
13function handleRequest(req, res) {
14 function send(err, body) {
15 if (err) {
16 return sendJson(req, res, err.message)
17 }
18
19 sendJson(req, res, body)
20 }
21
22 if (req.url === "/body") {
23 body(req, res, {}, send)
24 } else if (req.url === "/form") {
25 formBody(req, res, send)
26 } else if (req.url === "/json") {
27 jsonBody(req, {}, send)
28 } else if (req.url === "/any") {
29 anyBody(req, send)
30 }
31}
32
33function runTests(request, done) {
34 test("body works", function (t) {
35 t.end = after(2, t.end.bind(t))
36 testBody("/body", request, t)
37
38 request({
39 uri: "/any",
40 body: "foo"
41 }, function (err, res, body) {
42 t.equal(err, null)
43 t.equal(JSON.parse(body), "Could not parse content type header: ")
44 t.end()
45 })
46 })
47
48 test("form works", function (t) {
49 t.end = after(2, t.end.bind(t))
50 testFormBody("/form", request, t)
51 testFormBody("/any", request, t)
52 })
53
54 test("json works", function (t) {
55 t.end = after(2, t.end.bind(t))
56 testJsonBody("/json", request, t)
57 testJsonBody("/any", request, t)
58 })
59
60 .on("end", done)
61}
62
63function testBody(uri, request, t) {
64 request({
65 uri: uri,
66 body: "foo"
67 }, function (err, res, body) {
68 t.equal(err, null, "error is not null")
69
70 console.log("body", body, JSON.parse(body))
71 t.equal(JSON.parse(body), "foo", "body is incorrect")
72
73 t.end()
74 })
75}
76
77function testFormBody(uri, request, t) {
78 request({
79 uri: uri,
80 form: {
81 foo: "bar"
82 }
83 }, function (err, res, body) {
84 t.equal(err, null, "error is not null")
85
86 t.equal(JSON.parse(body).foo, "bar", "body is incorrect")
87
88 t.end()
89 })
90}
91
92function testJsonBody(uri, request, t) {
93 request({
94 uri: uri,
95 json: {
96 foo: "bar"
97 }
98 }, function (err, res, body) {
99 t.equal(err, null, "error is not null")
100
101 t.equal(body.foo, "bar", "body is incorrect")
102
103 t.end()
104 })
105}