import fc from 'fast-check'; import { describe, expect, it } from 'vitest'; import { lightboxEvent } from '../test/arbitraries'; import { closedLightbox, type LightboxEvent, lightboxReducer, type LightboxState, } from './lightboxReducer'; const open = (index: number, count: number): LightboxState => ({ open: true, index, count, }); describe('lightboxReducer', () => { it('opens at the chosen photo', () => { expect( lightboxReducer(closedLightbox, { type: 'open', index: 2, count: 5, }), ).toEqual(open(2, 5)); }); it('stays closed when there are no photos', () => { expect( lightboxReducer(closedLightbox, { type: 'open', index: 0, count: 0, }), ).toEqual(closedLightbox); }); it('wraps around when browsing past either end', () => { expect(lightboxReducer(open(4, 5), { type: 'next' })).toEqual( open(0, 5), ); expect(lightboxReducer(open(0, 5), { type: 'prev' })).toEqual( open(4, 5), ); }); it('jumps to the first and the last photo', () => { expect(lightboxReducer(open(3, 5), { type: 'first' })).toEqual( open(0, 5), ); expect(lightboxReducer(open(1, 5), { type: 'last' })).toEqual( open(4, 5), ); }); it('closes on close and when the list changes', () => { expect(lightboxReducer(open(1, 5), { type: 'close' })).toEqual( closedLightbox, ); expect( lightboxReducer(open(1, 5), { type: 'listChanged', count: 3 }), ).toEqual(closedLightbox); }); it('ignores browsing while closed', () => { for (const type of [ 'next', 'prev', 'first', 'last', 'close', ] as const) { expect(lightboxReducer(closedLightbox, { type })).toBe( closedLightbox, ); } }); // Stateful property: any sequence of events gives the same result as a // simple model that counts positions on a clock face it('follows the model for any sequence of events (stateful)', () => { type Model = { open: boolean; index: number; count: number }; const step = (model: Model, event: LightboxEvent): Model => { if (event.type === 'open') { return event.count < 1 ? { open: false, index: 0, count: 0 } : { open: true, index: ((event.index % event.count) + event.count) % event.count, count: event.count, }; } if (!model.open) return model; if (event.type === 'next') return { ...model, index: (model.index + 1) % model.count }; if (event.type === 'prev') return { ...model, index: (model.index + model.count - 1) % model.count, }; if (event.type === 'first') return { ...model, index: 0 }; if (event.type === 'last') return { ...model, index: model.count - 1 }; return { open: false, index: 0, count: 0 }; }; fc.assert( fc.property( fc.array(lightboxEvent, { maxLength: 40 }), (events) => { let state: LightboxState = closedLightbox; let model: Model = { open: false, index: 0, count: 0 }; for (const event of events) { state = lightboxReducer(state, event); model = step(model, event); expect(state.open).toBe(model.open); if (state.open) { expect(state.index).toBe(model.index); expect(state.count).toBe(model.count); expect(state.index).toBeGreaterThanOrEqual(0); expect(state.index).toBeLessThan(state.count); } } }, ), ); }); });