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
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function isJSONSerializable(value: any): boolean {
return false;
}
const t = typeof value;
if (t === "string" || t === "number" || t === "boolean" || t === null) {
if (value === null || t === "string" || t === "number" || t === "boolean") {
return true;
}
if (t !== "object") {
Expand Down
22 changes: 22 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { Readable } from "node:stream";
import { H3, HTTPError, readBody, serve } from "h3";
import { $fetch } from "../src/index.ts";
import { isJSONSerializable } from "../src/utils.ts";

describe("ofetch", () => {
let listener: ReturnType<typeof serve>;
Expand Down Expand Up @@ -525,3 +526,24 @@ describe("ofetch", () => {
});
});
});

describe("isJSONSerializable", () => {
it("treats null as serializable without throwing", () => {
// `typeof null` is "object", so the old `t === null` check was dead code
// and execution fell through to `value.buffer`, throwing on null.
// eslint-disable-next-line unicorn/no-null
const value = null;
expect(() => isJSONSerializable(value)).not.toThrow();
expect(isJSONSerializable(value)).toBe(true);
});

it("classifies common values", () => {
expect(isJSONSerializable(undefined)).toBe(false);
expect(isJSONSerializable("str")).toBe(true);
expect(isJSONSerializable(1)).toBe(true);
expect(isJSONSerializable({ a: 1 })).toBe(true);
expect(isJSONSerializable([1, 2])).toBe(true);
expect(isJSONSerializable(new Uint8Array())).toBe(false);
expect(isJSONSerializable(() => {})).toBe(false);
});
});