import fc from 'fast-check'; import { describe, expect, it } from 'vitest'; import { imagePositionAny, imagePositionInvalid, imagePositionValid, } from '../test/arbitraries'; import { normalizeImagePosition } from './normalizeImagePosition'; const CENTRE = '50% 50%'; // The shape every result has: two numbers with at most two decimals const SHAPE = /^(\d+(?:\.\d{1,2})?)% (\d+(?:\.\d{1,2})?)%$/; describe('normalizeImagePosition (examples)', () => { it('keeps a good value', () => { expect(normalizeImagePosition('50% 42%')).toBe('50% 42%'); expect(normalizeImagePosition('0% 100%')).toBe('0% 100%'); }); it('writes the numbers tidily and ignores extra whitespace', () => { expect(normalizeImagePosition('050.0% 42%')).toBe('50% 42%'); expect(normalizeImagePosition(' 12.50% 7.25% ')).toBe( '12.5% 7.25%', ); expect(normalizeImagePosition('50%\t42%')).toBe('50% 42%'); }); it('rounds tiny values instead of writing an exponent', () => { expect(normalizeImagePosition('0.0000001% 50%')).toBe('0% 50%'); }); it('falls back to the centre for anything else', () => { for (const bad of [ '120% 40%', '50 42', '50%', '-5% 10%', '1e1% 5%', '', 'center', ]) { expect(normalizeImagePosition(bad)).toBe(CENTRE); } expect(normalizeImagePosition(undefined)).toBe(CENTRE); expect(normalizeImagePosition(null)).toBe(CENTRE); expect(normalizeImagePosition(42)).toBe(CENTRE); }); }); describe('normalizeImagePosition (properties)', () => { it('always gives two numbers from 0 to 100 (invariant)', () => { fc.assert( fc.property(imagePositionAny, (value) => { const match = SHAPE.exec(normalizeImagePosition(value)); expect(match).not.toBeNull(); const [x, y] = [Number(match?.[1]), Number(match?.[2])]; expect(x >= 0 && x <= 100 && y >= 0 && y <= 100).toBe(true); }), ); }); it('does not change a value that is already normalised (idempotence)', () => { fc.assert( fc.property(imagePositionAny, (value) => { const once = normalizeImagePosition(value); expect(normalizeImagePosition(once)).toBe(once); }), ); }); it('reads any layout of whitespace as the plain form (round-trip)', () => { fc.assert( fc.property(imagePositionValid, ({ x, y, text }) => { expect(normalizeImagePosition(text)).toBe(`${x}% ${y}%`); }), ); }); it('gives exactly the centre for a value that is not acceptable (easy verification)', () => { fc.assert( fc.property(imagePositionInvalid, (value) => { expect(normalizeImagePosition(value)).toBe(CENTRE); }), ); }); it('never throws, whatever it is given', () => { fc.assert( fc.property(fc.anything(), (value) => { expect(typeof normalizeImagePosition(value)).toBe('string'); }), ); }); });