|
| 1 | +import EventEmitter from "node:events"; |
| 2 | +import { getPayload } from "../../src/middleware/node/get-payload.ts"; |
| 3 | + |
| 4 | +describe("getPayload", () => { |
| 5 | + it("returns a promise", () => { |
| 6 | + const request = new EventEmitter(); |
| 7 | + const promise = getPayload(request); |
| 8 | + |
| 9 | + expect(promise).toBeInstanceOf(Promise); |
| 10 | + }); |
| 11 | + |
| 12 | + it("resolves with a string when only receiving no chunk", async () => { |
| 13 | + const request = new EventEmitter(); |
| 14 | + const promise = getPayload(request); |
| 15 | + |
| 16 | + request.emit("end"); |
| 17 | + |
| 18 | + expect(await promise).toEqual(""); |
| 19 | + }); |
| 20 | + |
| 21 | + it("resolves with a string when only receiving one chunk", async () => { |
| 22 | + const request = new EventEmitter(); |
| 23 | + const promise = getPayload(request); |
| 24 | + |
| 25 | + request.emit("data", Buffer.from("foobar")); |
| 26 | + request.emit("end"); |
| 27 | + |
| 28 | + expect(await promise).toEqual("foobar"); |
| 29 | + }); |
| 30 | + |
| 31 | + it("resolves with a string when receiving multiple chunks", async () => { |
| 32 | + const request = new EventEmitter(); |
| 33 | + const promise = getPayload(request); |
| 34 | + |
| 35 | + request.emit("data", Buffer.from("foo")); |
| 36 | + request.emit("data", Buffer.from("bar")); |
| 37 | + request.emit("end"); |
| 38 | + |
| 39 | + expect(await promise).toEqual("foobar"); |
| 40 | + }); |
| 41 | + |
| 42 | + it("rejects with an error", async () => { |
| 43 | + const request = new EventEmitter(); |
| 44 | + const promise = getPayload(request); |
| 45 | + |
| 46 | + request.emit("error", new Error("test")); |
| 47 | + |
| 48 | + await expect(promise).rejects.toThrow("test"); |
| 49 | + }); |
| 50 | + |
| 51 | + it("resolves with a string with respecting the utf-8 encoding", async () => { |
| 52 | + const request = new EventEmitter(); |
| 53 | + const promise = getPayload(request); |
| 54 | + |
| 55 | + const doubleByteBuffer = Buffer.from("ݔ"); |
| 56 | + request.emit("data", doubleByteBuffer.subarray(0, 1)); |
| 57 | + request.emit("data", doubleByteBuffer.subarray(1, 2)); |
| 58 | + request.emit("end"); |
| 59 | + |
| 60 | + expect(await promise).toEqual("ݔ"); |
| 61 | + }); |
| 62 | + |
| 63 | + it("resolves with the body, if passed via the request", async () => { |
| 64 | + const request = new EventEmitter(); |
| 65 | + // @ts-ignore body is not part of EventEmitter, which we are using |
| 66 | + // to mock the request object |
| 67 | + request.body = "foo"; |
| 68 | + |
| 69 | + const promise = getPayload(request); |
| 70 | + |
| 71 | + // we emit data, to ensure that the body attribute is preferred |
| 72 | + request.emit("data", "bar"); |
| 73 | + request.emit("end"); |
| 74 | + |
| 75 | + expect(await promise).toEqual("foo"); |
| 76 | + }); |
| 77 | +}); |
0 commit comments