import { toDocument } from "./to-document"; import { BLOCKS, type Document } from "@contentful/rich-text-types"; const makeDocument = (text = "Hello"): Document => ({ nodeType: BLOCKS.DOCUMENT, data: {}, content: [ { nodeType: BLOCKS.PARAGRAPH, data: {}, content: [{ nodeType: "text", value: text, marks: [], data: {} }], }, ], }); describe("toDocument", () => { // ── Falsy inputs ───────────────────────────────────── it("returns null for null", () => { expect(toDocument(null)).toBeNull(); }); it("returns null for undefined", () => { expect(toDocument(undefined)).toBeNull(); }); it("returns null for empty string", () => { expect(toDocument("")).toBeNull(); }); it("returns null for 0", () => { expect(toDocument(0)).toBeNull(); }); it("returns null for false", () => { expect(toDocument(false)).toBeNull(); }); // ── REST/CDA Document ──────────────────────────────── it("returns Document directly when given a valid REST Document", () => { const doc = makeDocument(); expect(toDocument(doc)).toBe(doc); }); // ── GraphQL RichText { json: Document } ────────────── it("extracts Document from GraphQL format { json, links }", () => { const doc = makeDocument("GraphQL"); const graphql = { json: doc, links: { assets: [] } }; expect(toDocument(graphql)).toBe(doc); }); it("extracts Document from GraphQL format without links", () => { const doc = makeDocument("NoLinks"); expect(toDocument({ json: doc })).toBe(doc); }); it("returns null when json property is not a valid Document", () => { expect(toDocument({ json: "not-a-document" })).toBeNull(); }); it("returns null when json property is null", () => { expect(toDocument({ json: null })).toBeNull(); }); // ── Non-matching objects ───────────────────────────── it("returns null for an object without nodeType or json", () => { expect(toDocument({ foo: "bar" })).toBeNull(); }); it("returns null for an object with nodeType but no content", () => { expect(toDocument({ nodeType: BLOCKS.DOCUMENT })).toBeNull(); }); it("returns null for an array", () => { expect(toDocument([1, 2, 3])).toBeNull(); }); it("returns null for a number", () => { expect(toDocument(42)).toBeNull(); }); it("returns null for a non-empty string", () => { expect(toDocument("hello")).toBeNull(); }); });