Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ export function isPayloadMethod(method = "GET"): boolean {
}

export function isJSONSerializable(value: any): boolean {
if (value === undefined) {
if (value === undefined || value === null) {
return false;
}
const t = typeof value;
if (t === "string" || t === "number" || t === "boolean" || t === null) {
if (t === "string" || t === "number" || t === "boolean") {
return true;
}
if (t !== "object") {
Expand Down
43 changes: 43 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -525,3 +525,46 @@ describe("ofetch", () => {
});
});
});

describe("isJSONSerializable", () => {
let isJSONSerializable: any;

beforeAll(async () => {
const utils = await import("../src/utils.ts");
isJSONSerializable = utils.isJSONSerializable;
});

it("returns false for null", () => {
expect(isJSONSerializable(null)).toBe(false); // eslint-disable-line unicorn/no-null
});

it("returns false for undefined", () => {
expect(isJSONSerializable(undefined)).toBe(false);
});

it("returns true for primitive types", () => {
expect(isJSONSerializable("string")).toBe(true);
expect(isJSONSerializable(123)).toBe(true);
expect(isJSONSerializable(true)).toBe(true);
expect(isJSONSerializable(false)).toBe(true);
});

it("returns true for plain objects and arrays", () => {
expect(isJSONSerializable({})).toBe(true);
expect(isJSONSerializable([])).toBe(true);
expect(isJSONSerializable({ a: 1 })).toBe(true);
});

it("returns false for TypedArray (has .buffer property)", () => {
expect(isJSONSerializable(new Uint8Array(10))).toBe(false);
});

it("returns false for ArrayBuffer", () => {
expect(isJSONSerializable(new ArrayBuffer(10))).toBe(false);
});

it("returns false for FormData and URLSearchParams", () => {
expect(isJSONSerializable(new FormData())).toBe(false);
expect(isJSONSerializable(new URLSearchParams())).toBe(false);
});
});