integration.js 2.4 KB

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