|
| 1 | +import test, { before, after } from "ava" |
| 2 | +import resumer from "resumer" |
| 3 | +import FormData from "form-data" |
| 4 | +import * as stream from "stream" |
| 5 | +import { extractContentType, getTotalBytes } from "./src" |
| 6 | +import express from "express" |
| 7 | +import getPort from "get-port" // eslint-disable-line import/default |
| 8 | +import { Request } from "node-fetch" |
| 9 | +import Blob from "fetch-blob" |
| 10 | +const app = express() |
| 11 | + |
| 12 | +before(async (t) => { |
| 13 | + t.context.port = await getPort() |
| 14 | + t.context.server = app.listen(t.context.port) |
| 15 | + t.context.baseURL = `http://localhost:${t.context.port}/` |
| 16 | +}) |
| 17 | + |
| 18 | +after.always((t) => t.context.server.close()) |
| 19 | + |
| 20 | +test("should calculate content length and extract content type for each body type", (t) => { |
| 21 | + const url = `${t.context.baseURL}hello` |
| 22 | + const bodyContent = "a=1" |
| 23 | + |
| 24 | + let streamBody = resumer().queue(bodyContent).end() |
| 25 | + streamBody = streamBody.pipe(new stream.PassThrough()) |
| 26 | + const streamRequest = new Request(url, { |
| 27 | + method: "POST", |
| 28 | + body: streamBody, |
| 29 | + size: 1024, |
| 30 | + }) |
| 31 | + |
| 32 | + const blobBody = new Blob([bodyContent], { type: "text/plain" }) |
| 33 | + const blobRequest = new Request(url, { |
| 34 | + method: "POST", |
| 35 | + body: blobBody, |
| 36 | + size: 1024, |
| 37 | + }) |
| 38 | + |
| 39 | + const formBody = new FormData() |
| 40 | + formBody.append("a", "1") |
| 41 | + const formRequest = new Request(url, { |
| 42 | + method: "POST", |
| 43 | + body: formBody, |
| 44 | + size: 1024, |
| 45 | + }) |
| 46 | + |
| 47 | + const bufferBody = Buffer.from(bodyContent) |
| 48 | + const bufferRequest = new Request(url, { |
| 49 | + method: "POST", |
| 50 | + body: bufferBody, |
| 51 | + size: 1024, |
| 52 | + }) |
| 53 | + |
| 54 | + const stringRequest = new Request(url, { |
| 55 | + method: "POST", |
| 56 | + body: bodyContent, |
| 57 | + size: 1024, |
| 58 | + }) |
| 59 | + |
| 60 | + const nullRequest = new Request(url, { |
| 61 | + method: "GET", |
| 62 | + body: null, |
| 63 | + size: 1024, |
| 64 | + }) |
| 65 | + |
| 66 | + t.is(getTotalBytes(streamRequest), null) |
| 67 | + t.is(getTotalBytes(blobRequest), blobBody.size) |
| 68 | + t.not(getTotalBytes(formRequest), null) |
| 69 | + t.is(getTotalBytes(bufferRequest), bufferBody.length) |
| 70 | + t.is(getTotalBytes(stringRequest), bodyContent.length) |
| 71 | + t.is(getTotalBytes(nullRequest), 0) |
| 72 | + |
| 73 | + t.is(extractContentType(streamBody), null) |
| 74 | + t.is(extractContentType(blobBody), "text/plain") |
| 75 | + t.true(extractContentType(formBody).startsWith("multipart/form-data")) |
| 76 | + t.is(extractContentType(bufferBody), null) |
| 77 | + t.is(extractContentType(bodyContent), "text/plain;charset=UTF-8") |
| 78 | + t.is(extractContentType(null), null) |
| 79 | +}) |
0 commit comments