import { notFound } from "next/navigation"; import { ImageResponse } from "next/og"; import { isValidElement } from "react"; import { OG_SIZE, OgCard } from "@/lib/og-card"; import { caseStudies } from "@/lib/site-content"; import Image from "./opengraph-image"; /** * Testes de caminhos-base de Image (imagem de compartilhamento do case): * slug desconhecido, id da imagem diferente do case, case de cliente e projeto de laboratório. */ jest.mock("next/navigation", () => ({ notFound: jest.fn(() => { throw new Error("NEXT_NOT_FOUND"); }), })); jest.mock("next/og", () => ({ ImageResponse: jest.fn() })); const mockedImageResponse = jest.mocked(ImageResponse); beforeEach(() => { jest.mocked(notFound).mockClear(); mockedImageResponse.mockClear(); }); function getCase(id: string) { const caseStudy = caseStudies.find((item) => item.id === id); if (!caseStudy) throw new Error(`Missing case ${id}`); return caseStudy; } function renderImage(slug: string, imageId: string) { return Image({ params: Promise.resolve({ slug }), id: Promise.resolve(imageId), }); } function sentCard() { const [element, options] = mockedImageResponse.mock.calls[0]; if (!isValidElement>(element)) { throw new Error("ImageResponse did not receive an element"); } return { card: element, options }; } describe("opengraph-image Image", () => { it("path: client case with the matching image id -> card labelled as a client case", async () => { const caseStudy = getCase("sev-modaintima"); await renderImage(caseStudy.id, caseStudy.id); expect(notFound).not.toHaveBeenCalled(); expect(mockedImageResponse).toHaveBeenCalledTimes(1); const { card, options } = sentCard(); expect(card.type).toBe(OgCard); expect(card.props).toMatchObject({ eyebrow: "Case de cliente", title: caseStudy.title, description: caseStudy.summary, }); expect(card.props.backgroundImage).toMatch(/^data:image\/jpeg;base64,/); expect(options).toEqual(OG_SIZE); }); it("path: unknown slug -> notFound() and no image", async () => { await expect(renderImage("nao-existe", "nao-existe")).rejects.toThrow( "NEXT_NOT_FOUND", ); expect(notFound).toHaveBeenCalledTimes(1); expect(mockedImageResponse).not.toHaveBeenCalled(); }); it("path: known slug but another case's image id -> notFound() and no image", async () => { await expect(renderImage("sev-modaintima", "lavacao-047")).rejects.toThrow( "NEXT_NOT_FOUND", ); expect(notFound).toHaveBeenCalledTimes(1); expect(mockedImageResponse).not.toHaveBeenCalled(); }); it("path: laboratory case -> card labelled as a laboratory project, no cover when none is recorded", async () => { const caseStudy = getCase("twins-lab"); await renderImage(caseStudy.id, caseStudy.id); const { card } = sentCard(); expect(card.props).toMatchObject({ eyebrow: "Projeto de laboratório", title: caseStudy.title, }); expect(card.props.backgroundImage).toBeUndefined(); }); });