diff --git a/packages/util-body-length-browser/src/index.spec.ts b/packages/util-body-length-browser/src/index.spec.ts new file mode 100644 index 000000000000..1fb4c5d3e56f --- /dev/null +++ b/packages/util-body-length-browser/src/index.spec.ts @@ -0,0 +1,23 @@ +import { calculateBodyLength } from "./"; + +const arrayBuffer = new ArrayBuffer(1); +const typedArray = new Uint8Array(1); +const view = new DataView(arrayBuffer); + +describe("caclulateBodyLength", () => { + it("should handle string inputs", () => { + expect(calculateBodyLength("foo")).toEqual(3); + }); + + it("should handle string inputs with multi-byte characters", () => { + expect(calculateBodyLength("2。")).toEqual(4); + }); + + it("should handle inputs with byteLengths", () => { + expect(calculateBodyLength(arrayBuffer)).toEqual(1); + }); + + it("should handle TypedArray inputs", () => { + expect(calculateBodyLength(typedArray)).toEqual(1); + }); +}); diff --git a/packages/util-body-length-browser/src/index.ts b/packages/util-body-length-browser/src/index.ts index 5daf1ef3617e..3ab61ebf1e63 100644 --- a/packages/util-body-length-browser/src/index.ts +++ b/packages/util-body-length-browser/src/index.ts @@ -1,6 +1,6 @@ export function calculateBodyLength(body: any): number | undefined { if (typeof body === "string") { - return body.length; + return new Blob([body]).size; } else if (typeof body.byteLength === "number") { // handles Uint8Array, ArrayBuffer, Buffer, and ArrayBufferView return body.byteLength; diff --git a/packages/util-body-length-browser/tsconfig.json b/packages/util-body-length-browser/tsconfig.json index ea8af8858555..4fe7c1e7a45f 100644 --- a/packages/util-body-length-browser/tsconfig.json +++ b/packages/util-body-length-browser/tsconfig.json @@ -11,7 +11,8 @@ "es2015.promise", "es2015.collection", "es2015.iterable", - "es2015.symbol.wellknown" + "es2015.symbol.wellknown", + "dom" ], "rootDir": "./src", "outDir": "./build",