Files
ipal-kit/test/blockLibraryPayload.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 2d1cc0e77d Block library: 15 blocks, registry, primitives, templates, manifest, eject
- @intecion/ipal-kit/blocks: libraryBlocks() opt-in, one builder per block, field
  builders, option merging, blockLibraryManifest, faqItemsFromLayout
- @intecion/ipal-kit/blocks/rsc: createBlockRegistry, the block components and UI
  primitives (token utilities only; next/image and next/link passed in)
- @intecion/ipal-kit/templates: 10 page templates as createSeeder data
- createSeeder: { $form: title } references
- ipal-blocks eject <block>
- tests: options, rendering and a11y per block, Payload + seeding, GraphQL, admin
  wording, schema snapshot (versioning), eject imports
- shorter admin labels: link "New tab", table of contents "Show contents"

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:05:47 +01:00

135 lines
6.3 KiB
TypeScript

import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { LIBRARY_BLOCK_SLUGS, libraryBlocks } from '../src/exports/blocks.js'
import { createSeeder } from '../src/exports/seed.js'
import { pageTemplates, systemPageRefs } from '../src/exports/templates.js'
import { ipalKit } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
/**
* The library in a real Payload: every block in a pages `layout`, every page template
* seeded through createSeeder in both locales (forms by `$form`, pages by `$page`).
*/
describe('block library in Payload', () => {
let payload: Payload
const lines: string[] = []
beforeAll(async () => {
vi.stubEnv('DATABASE_URI', 'file::memory:')
const config = buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{
name: 'layout',
type: 'blocks',
blocks: libraryBlocks({ ...Object.fromEntries(LIBRARY_BLOCK_SLUGS.map((s) => [s, true])), testimonials: { collection: 'testimonials' } }),
},
],
},
{
slug: 'posts',
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', localized: true },
],
},
{ slug: 'testimonials', fields: [{ name: 'quote', type: 'textarea' }, { name: 'heading', type: 'text' }] },
{ slug: 'media', fields: [{ name: 'alt', type: 'text' }], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-blocks') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
localization: { defaultLocale: 'pl', fallback: true, locales: ['pl', 'en'] },
plugins: [
ipalKit({
content: { collections: [{ slug: 'posts' }] },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] },
pages: { slug: 'pages' },
twoFactor: false,
} as never),
],
secret: 'block-library-test',
telemetry: false,
})
payload = await getPayload({ config })
}, 60_000)
afterAll(async () => {
vi.unstubAllEnvs()
await payload?.destroy()
})
test('every template seeds into the schema, with forms and pages linked', async () => {
const seed = createSeeder(payload, { dryRun: false, log: (l) => lines.push(l), update: false })
const formResult = await seed.upsertBy('forms', { title: 'Contact form' }, {
confirmationMessage: { root: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Thanks', version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 }], direction: 'ltr', format: '', indent: 0, version: 1 } },
confirmationType: 'message',
fields: [{ name: 'name', blockType: 'text', label: 'Name', required: true }],
title: 'Contact form',
})
expect(formResult).toMatchObject({ status: 'create' })
const form = { $form: 'Contact form' }
const results = await seed.upsertBySlug('pages', [
pageTemplates.home(),
pageTemplates.about(),
pageTemplates.services(),
pageTemplates.service({ form }),
pageTemplates.contact({ form }),
pageTemplates.blogIndex(),
pageTemplates.legal('privacyPolicy'),
pageTemplates.legal('termsOfService'),
pageTemplates.cookiePolicy(),
pageTemplates.notFound(),
])
expect(results.filter((r) => r.status === 'error')).toEqual([])
expect(results.every((r) => r.status === 'create')).toBe(true)
await seed.fillGlobal('site-settings', { siteName: 'Test site', ...systemPageRefs({ homepage: 'start', notFound: 'nie-znaleziono', privacyPolicy: 'polityka-prywatnosci' }) })
expect(lines.filter((l) => /error/.test(l))).toEqual([])
expect(seed.summary().errors).toBe(0)
const { docs } = await payload.find({ collection: 'pages', depth: 1, locale: 'en', where: { slug: { equals: 'contact' } } })
const contact = docs[0] as unknown as { layout: { blockType: string; form?: { title?: string } }[] }
expect(contact.layout.map((b) => b.blockType)).toEqual(['hero', 'contact', 'faq'])
expect(contact.layout[1].form?.title).toBe('Contact form')
const home = await payload.find({ collection: 'pages', depth: 0, locale: 'pl', where: { slug: { equals: 'start' } } })
const hero = (home.docs[0] as unknown as { layout: { blockType: string; links: { link: { page: unknown } }[] }[] }).layout[0]
const contactId = (await payload.find({ collection: 'pages', depth: 0, where: { slug: { equals: 'kontakt' } } })).docs[0].id
expect(hero.links[0].link.page).toBe(contactId)
const settings = (await payload.findGlobal({ slug: 'site-settings' as never, depth: 0 })) as { homepage?: unknown }
expect(settings.homepage).toBe(home.docs[0].id)
})
test('a template for a block that is off leaves it out instead of failing', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const seed = createSeeder(payload, { dryRun: false, log: () => {}, update: false })
const page = pageTemplates.about({ slug: { en: 'about-short', pl: 'o-nas-krotko' }, blocks: { cta: 'cta', hero: 'hero' } })
const [result] = await seed.upsertBySlug('pages', [page])
expect(result.status).toBe('create')
expect(warn).toHaveBeenCalled()
warn.mockRestore()
})
test('$form that does not exist is an error, not a silent empty relation', async () => {
const seed = createSeeder(payload, { dryRun: false, log: () => {}, update: false })
const [result] = await seed.upsertBySlug('pages', [pageTemplates.contact({ slug: { en: 'contact-2', pl: 'kontakt-2' }, form: { $form: 'Missing form' } })])
expect(result.status).toBe('error')
expect(result.note).toMatch(/\$form "Missing form" not found/)
})
})