import fc from 'fast-check'; import { describe, expect, it } from 'vitest'; import aboutContent from './content/aboutContent'; import shootTypes from './content/shootTypes'; import siteContent from './content/siteContent'; import { emailAddress } from './lib/emailAddress'; import { visibleSocials } from './lib/visibleSocials'; import type { RoutePath } from './navigation'; import { aboutPage, absoluteUrl, areaServed, businessId, canonicalUrl, defaultOgImage, jsonLdScript, pageHead, person, personId, professionalService, shootServices, siteHead, siteUrl, structuredDataScript, webPage, type WebPageType, } from './seo'; import sitePages from './sitePages'; import { anySiteContent, knowsAboutEntries, routePath, uniqueShootTypes, } from './test/arbitraries'; const meta = (head: ReturnType, key: string) => head.meta.find( (m) => ('name' in m && m.name === key) || ('property' in m && m.property === key), ); describe('canonicalUrl', () => { it('maakt een absolute URL zonder slash, query of hash', () => { expect(canonicalUrl('/')).toBe(`${siteUrl}/`); expect(canonicalUrl('')).toBe(`${siteUrl}/`); expect(canonicalUrl('/portfolio/')).toBe(`${siteUrl}/portfolio`); expect(canonicalUrl('/contact?x=1#top')).toBe(`${siteUrl}/contact`); expect(canonicalUrl('portfolio')).toBe(`${siteUrl}/portfolio`); }); it('is idempotent', () => { fc.assert( fc.property( routePath, fc.constantFrom('', '/', '?a=1', '#x'), (path, suffix) => { const once = canonicalUrl(path + suffix); expect(canonicalUrl(once.slice(siteUrl.length))).toBe(once); }, ), ); }); it('begint met siteUrl en eindigt alleen bij de root op een slash (invariant)', () => { fc.assert( fc.property(fc.string(), (path) => { const url = canonicalUrl(path); const rest = url.slice(siteUrl.length); return ( url.startsWith(siteUrl + '/') && !/[?#]/.test(rest) && (rest === '/' || !rest.endsWith('/')) ); }), ); }); }); describe('pageHead', () => { it('zet titel, canonical en preview voor de homepage, zonder robots-tag', () => { const head = pageHead('/'); expect(head.meta[0]).toEqual({ title: 'Lifestyle fotograaf in Huizen | Andrea Slop Fotografie', }); expect(head.links).toEqual([{ rel: 'canonical', href: `${siteUrl}/` }]); expect(meta(head, 'og:url')).toMatchObject({ content: `${siteUrl}/` }); expect(meta(head, 'og:image')).toMatchObject({ content: `${siteUrl}/og-image.jpg`, }); expect(meta(head, 'robots')).toBeUndefined(); }); it('zet noindex op een placeholder', () => { const head = pageHead('/portfolio'); expect(meta(head, 'robots')).toMatchObject({ content: 'noindex' }); expect(head.links[0].href).toBe(`${siteUrl}/portfolio`); }); }); describe('jsonLdScript', () => { it('geeft na parsen dezelfde data terug (round-trip)', () => { fc.assert( fc.property(fc.jsonValue(), (value) => { expect(JSON.parse(jsonLdScript(value))).toEqual( JSON.parse(JSON.stringify(value)), ); }), ); }); it('bevat nooit < of >, dus nooit een sluitende script-tag (invariant)', () => { fc.assert( fc.property(fc.jsonValue(), fc.string(), (value, text) => { const out = jsonLdScript({ value, text: text + '' }); return !/[<>]/.test(out); }), ); }); }); describe('professionalService en siteHead', () => { it('beschrijft de fotograaf zonder e-mailadres', () => { const data = professionalService(siteContent); expect(data['@type']).toBe('ProfessionalService'); expect(data.address.addressLocality).toBe('Huizen'); expect(data.sameAs).toEqual(siteContent.socials.map((s) => s.href)); expect(JSON.stringify(data)).not.toContain('@andreaslop'); }); it('serves Huizen and Gooi en Vechtstreek', () => { expect(professionalService(siteContent).areaServed).toEqual([ { '@type': 'City', name: 'Huizen' }, { '@type': 'AdministrativeArea', name: 'Gooi en Vechtstreek' }, ]); }); it('laat ongeldige socials weg uit sameAs', () => { const data = professionalService({ ...siteContent, socials: [{ platform: 'facebook', href: 'http://onveilig.nl' }], }); expect(data.sameAs).toEqual([]); }); it('zet de gestructureerde data als ld+json-script', () => { const head = siteHead(siteContent); expect(head.scripts[0].type).toBe('application/ld+json'); expect(JSON.parse(head.scripts[0].children)['@type']).toBe( 'ProfessionalService', ); }); }); describe('areaServed', () => { it('keeps every named area, trimmed and in order (invariant)', () => { fc.assert( fc.property(anySiteContent, (site) => { const named = site.serviceArea.filter( (area) => area.name.trim() !== '', ); expect(areaServed(site.serviceArea)).toEqual( named.map((area) => ({ '@type': area.type, name: area.name.trim(), })), ); }), ); }); it('only produces towns and regions (invariant)', () => { fc.assert( fc.property(anySiteContent, (site) => areaServed(site.serviceArea).every((place) => ['City', 'AdministrativeArea'].includes(place['@type']), ), ), ); }); }); describe('pageHead for the about page', () => { it('is indexed, with its own title, description and preview image', () => { const head = pageHead('/over-mij'); expect(head.meta[0]).toEqual({ title: 'Over mij – fotograaf in Huizen | Andrea Slop Fotografie', }); expect(meta(head, 'robots')).toBeUndefined(); expect(meta(head, 'description')).toMatchObject({ content: sitePages['/over-mij'].description, }); expect(meta(head, 'og:image')).toMatchObject({ content: `${siteUrl}/og-over-mij.jpg`, }); expect(head.links[0].href).toBe(`${siteUrl}/over-mij`); }); it('keeps title and description within what search engines show', () => { const page = sitePages['/over-mij']; expect( `${page.title} | Andrea Slop Fotografie`.length, ).toBeLessThanOrEqual(60); expect(page.description.length).toBeLessThanOrEqual(155); }); }); describe('structured data about Andrea', () => { const image = `${siteUrl}/og-over-mij.jpg`; it('describes Andrea from the page content and the site socials', () => { expect(person(aboutContent.person, siteContent, image)).toEqual({ '@type': 'Person', '@id': personId, name: 'Andrea Slop', jobTitle: 'Lifestyle fotograaf', image, address: { '@type': 'PostalAddress', addressLocality: 'Huizen', addressCountry: 'NL', }, url: `${siteUrl}/over-mij`, worksFor: { '@id': businessId }, knowsAbout: [ 'Newbornfotografie', 'Zwangerschapsfotografie', 'Gezinsfotografie', ], sameAs: siteContent.socials.map((social) => social.href), }); }); it('leaves out empty lists instead of writing them', () => { const data = person( { ...aboutContent.person, knowsAbout: [' ', ''] }, { ...siteContent, socials: [] }, image, ); expect(data).not.toHaveProperty('knowsAbout'); expect(data).not.toHaveProperty('sameAs'); }); it('links Andrea and the business both ways (invariant)', () => { fc.assert( fc.property(anySiteContent, (site) => { const business = professionalService(site); const andrea = person(aboutContent.person, site, image); expect(business['@id']).toBe(businessId); expect(business.founder['@id']).toBe(andrea['@id']); expect(andrea.worksFor['@id']).toBe(business['@id']); }), ); }); it('lists exactly the valid https socials in sameAs (invariant)', () => { fc.assert( fc.property(anySiteContent, (site) => { const valid = visibleSocials(site.socials).map((s) => s.href); const andrea = person(aboutContent.person, site, image); expect(andrea.sameAs ?? []).toEqual(valid); }), ); }); it('lists the cleaned specialisations in knowsAbout (invariant)', () => { fc.assert( fc.property(knowsAboutEntries, (entries) => { const andrea = person( { ...aboutContent.person, knowsAbout: entries }, siteContent, image, ); const list = andrea.knowsAbout ?? []; expect( list.every( (entry) => entry === entry.trim() && entry !== '', ), ).toBe(true); expect(new Set(list).size).toBe(list.length); }), ); }); it('never contains the e-mail address, on any page (invariant)', () => { fc.assert( fc.property(anySiteContent, (site) => { const address = emailAddress(site.email); const out = jsonLdScript( aboutPage('/over-mij', aboutContent.person, site), ) + jsonLdScript(professionalService(site)); return address === null || !out.includes(address); }), ); }); it('matches the page registry and canonical URL (invariant)', () => { fc.assert( fc.property(anySiteContent, (site) => { const page = aboutPage('/over-mij', aboutContent.person, site); expect(page['@id']).toBe(canonicalUrl('/over-mij')); expect(page.url).toBe(canonicalUrl('/over-mij')); expect(page.name).toBe(sitePages['/over-mij'].title); expect(page.description).toBe( sitePages['/over-mij'].description, ); expect(page.mainEntity.image).toBe(image); }), ); }); it('falls back to the site preview image for a page without its own', () => { const page = aboutPage('/portfolio', aboutContent.person, siteContent); expect(page.mainEntity.image).toBe(`${siteUrl}/og-image.jpg`); }); it('wraps data in an escaped ld+json script tag', () => { const script = structuredDataScript({ name: '' }); expect(script.type).toBe('application/ld+json'); expect(script.children).not.toMatch(/[<>]/); expect(JSON.parse(script.children)).toEqual({ name: '' }); }); }); describe('webPage', () => { const paths = Object.keys(sitePages) as RoutePath[]; const anyPath = fc.constantFrom(...paths); const anyType = fc.constantFrom( 'WebPage', 'AboutPage', 'ContactPage', 'ImageGallery', 'CollectionPage', ); const baseKeys = [ '@context', '@type', '@id', 'url', 'name', 'description', 'inLanguage', ]; // Page-specific fields: any JSON, under keys the base does not use const anyExtra = fc.dictionary( fc.string().filter((key) => !baseKeys.includes(key)), fc.jsonValue(), ); it('describes a page from the registry', () => { expect( webPage('ContactPage', '/contact', { about: { '@id': businessId }, }), ).toEqual({ '@context': 'https://schema.org', '@type': 'ContactPage', '@id': `${siteUrl}/contact`, url: `${siteUrl}/contact`, name: sitePages['/contact'].title, description: sitePages['/contact'].description, inLanguage: 'nl-NL', about: { '@id': businessId }, }); }); it('needs no extra fields', () => { expect(webPage('WebPage', '/')).not.toHaveProperty('mainEntity'); expect(webPage('WebPage', '/')['@id']).toBe(`${siteUrl}/`); }); it('takes name, description and URL from the registry (invariant)', () => { fc.assert( fc.property(anyType, anyPath, (type, path) => { const page = webPage(type, path); expect(page['@context']).toBe('https://schema.org'); expect(page['@type']).toBe(type); expect(page['@id']).toBe(canonicalUrl(path)); expect(page.url).toBe(canonicalUrl(path)); expect(page.name).toBe(sitePages[path].title); expect(page.description).toBe(sitePages[path].description); expect(page.inLanguage).toBe('nl-NL'); }), ); }); it('keeps every extra field as given (invariant)', () => { fc.assert( fc.property(anyType, anyPath, anyExtra, (type, path, extra) => { const page: Record = webPage( type, path, extra, ); for (const [key, value] of Object.entries(extra)) { expect(page[key]).toEqual(value); } }), ); }); it('survives the ld+json script unchanged (round trip)', () => { fc.assert( fc.property(anyType, anyPath, anyExtra, (type, path, extra) => { const page = webPage(type, path, extra); expect(JSON.parse(jsonLdScript(page))).toEqual( JSON.parse(JSON.stringify(page)), ); }), ); }); // aboutPage as it was before it used webPage, kept as the oracle for the // rebuilt version function previousAboutPage( path: RoutePath, content: Parameters[1], site: Parameters[2], ) { const page = sitePages[path]; const image = siteUrl + (page.ogImage ?? defaultOgImage).path; return { '@context': 'https://schema.org', '@type': 'AboutPage', '@id': canonicalUrl(path), url: canonicalUrl(path), name: page.title, description: page.description, inLanguage: 'nl-NL', mainEntity: person(content, site, image), }; } it('leaves the about page data exactly as it was (oracle)', () => { fc.assert( fc.property( anyPath, anySiteContent, knowsAboutEntries, (path, site, knowsAbout) => { const content = { ...aboutContent.person, knowsAbout }; expect(aboutPage(path, content, site)).toEqual( previousAboutPage(path, content, site), ); }, ), ); }); }); describe('absoluteUrl', () => { it('makes a bundled image path absolute and keeps absolute URLs', () => { expect(absoluteUrl('/assets/newborn-abc.jpg')).toBe( `${siteUrl}/assets/newborn-abc.jpg`, ); expect(absoluteUrl('assets/x.jpg')).toBe(`${siteUrl}/assets/x.jpg`); expect(absoluteUrl('https://cdn.example.nl/x.jpg')).toBe( 'https://cdn.example.nl/x.jpg', ); }); it('always gives an https URL, and applying it twice changes nothing (invariant, idempotency)', () => { fc.assert( fc.property(fc.oneof(fc.webPath(), fc.webUrl()), (src) => { const once = absoluteUrl(src); expect(once).toMatch(/^https?:\/\//); expect(absoluteUrl(once)).toBe(once); }), ); }); }); describe('shootServices', () => { const page = `${siteUrl}/soorten-fotoshoots`; it('lists the five shoots as services of the business, without prices', () => { const list = shootServices(shootTypes, siteContent); expect(list.numberOfItems).toBe(5); const services = list.itemListElement.map((element) => element.item); expect(services.map((service) => service['@id'])).toEqual([ `${page}#newborn`, `${page}#zwangerschap`, `${page}#gezin`, `${page}#loveshoot`, `${page}#portret`, ]); expect(services[0]).toMatchObject({ '@type': 'Service', name: 'Newbornshoot', serviceType: 'Newbornshoot', provider: { '@id': businessId }, areaServed: [ { '@type': 'City', name: 'Huizen' }, { '@type': 'AdministrativeArea', name: 'Gooi en Vechtstreek' }, ], }); // Only the first paragraph: the newborn invitation is not a description expect(services[0].description).toBe(shootTypes[0].paragraphs[0]); expect(services[0].image).toMatch(/^https:\/\/andreaslop\.nl\//); expect(JSON.stringify(list)).not.toMatch(/offers|price/i); }); it('fits in the page data built with webPage', () => { const data = webPage('WebPage', '/soorten-fotoshoots', { mainEntity: shootServices(shootTypes, siteContent), }); expect(data['@id']).toBe(page); expect(data.mainEntity.itemListElement).toHaveLength(5); }); it('has one item per shoot, numbered in order (invariant)', () => { fc.assert( fc.property(uniqueShootTypes, anySiteContent, (shoots, site) => { const list = shootServices(shoots, site); expect(list.numberOfItems).toBe(shoots.length); expect( list.itemListElement.map((element) => element.position), ).toEqual(shoots.map((_, index) => index + 1)); expect( list.itemListElement.map((element) => element.item.name), ).toEqual(shoots.map((shoot) => shoot.shootLabel)); }), ); }); it('gives every service its own anchor as @id (invariant)', () => { fc.assert( fc.property(uniqueShootTypes, anySiteContent, (shoots, site) => { const ids = shootServices(shoots, site).itemListElement.map( (element) => element.item['@id'], ); expect(new Set(ids).size).toBe(ids.length); ids.forEach((id, index) => expect(id).toBe(`${page}#${shoots[index].id}`), ); }), ); }); it('is always provided by the business in its service area, described by the first paragraph (invariant)', () => { fc.assert( fc.property(uniqueShootTypes, anySiteContent, (shoots, site) => { shootServices(shoots, site).itemListElement.forEach( ({ item }, index) => { expect(item.provider).toEqual({ '@id': businessId }); expect(item.areaServed).toEqual( areaServed(site.serviceArea), ); expect(item.description).toBe( shoots[index].paragraphs[0], ); }, ); }), ); }); it('never contains the e-mail address or a price (invariant)', () => { fc.assert( fc.property(uniqueShootTypes, anySiteContent, (shoots, site) => { const address = emailAddress(site.email); const out = jsonLdScript(shootServices(shoots, site)); return ( (address === null || !out.includes(address)) && !/"(offers|price)"/.test(out) ); }), ); }); });