import fc from 'fast-check'; import { describe, expect, it } from 'vitest'; import packages from '../content/packages'; import { uniquePackages } from '../test/arbitraries'; import { packageFromSearch } from './packageFromSearch'; // Random upper/lower case per letter, plus spaces around const mangled = (id: string) => fc .tuple( fc.array(fc.boolean(), { minLength: id.length, maxLength: id.length, }), fc.constantFrom('', ' ', ' '), fc.constantFrom('', ' ', '\t'), ) .map( ([upper, before, after]) => before + [...id] .map((char, i) => (upper[i] ? char.toUpperCase() : char)) .join('') + after, ); describe('packageFromSearch', () => { it('finds a package by id, ignoring case and spaces', () => { expect(packageFromSearch('newborn', packages)).toBe('newborn'); expect(packageFromSearch(' Gezin ', packages)).toBe('gezin'); }); it('ignores unknown or non-text values', () => { expect(packageFromSearch('bruiloft', packages)).toBeUndefined(); expect(packageFromSearch('', packages)).toBeUndefined(); expect(packageFromSearch(123, packages)).toBeUndefined(); expect(packageFromSearch(['newborn'], packages)).toBeUndefined(); expect(packageFromSearch(undefined, packages)).toBeUndefined(); }); it('only returns undefined or one of the given ids (invariant)', () => { fc.assert( fc.property(fc.anything(), uniquePackages, (value, list) => { const result = packageFromSearch(value, list); expect( result === undefined || list.some((pkg) => pkg.id === result), ).toBe(true); }), ); }); it('finds every package in any letter case with spaces around (oracle)', () => { fc.assert( fc.property( uniquePackages .filter((list) => list.length > 0) .chain((list) => fc .integer({ min: 0, max: list.length - 1 }) .chain((i) => mangled(list[i].id).map( (value) => [list, list[i].id, value] as const, ), ), ), ([list, id, value]) => { expect(packageFromSearch(value, list)).toBe(id); }, ), ); }); it('never matches a value that is not text (invariant)', () => { fc.assert( fc.property( fc.anything().filter((value) => typeof value !== 'string'), uniquePackages, (value, list) => { expect(packageFromSearch(value, list)).toBeUndefined(); }, ), ); }); it('gives the same id when its result is fed back in (idempotent)', () => { fc.assert( fc.property(fc.string(), uniquePackages, (value, list) => { const once = packageFromSearch(value, list); expect(packageFromSearch(once, list)).toBe(once); }), ); }); });