app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

search-listings.test.ts (8867B)


      1 import { render } from 'svelte/server';
      2 import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
      3 import ListingRow from '../../../src/lib/components/ListingRow.svelte';
      4 import SourceStatus from '../../../src/lib/components/SourceStatus.svelte';
      5 import type { ListingView } from '../../../src/lib/catalog/listing-view.ts';
      6 import { encodeProductReference } from '../../../src/lib/nostr/references.ts';
      7 import { finalizeEvent } from 'applesauce-core/helpers';
      8 function listing(): ListingView {
      9   const key = crypto.getRandomValues(new Uint8Array(32));
     10   let pubkey: string;
     11   try {
     12     pubkey = finalizeEvent(
     13       { kind: 0, created_at: 1, tags: [], content: '{}' },
     14       key
     15     ).pubkey;
     16   } finally {
     17     key.fill(0);
     18   }
     19   return {
     20     eventId: 'a'.repeat(64),
     21     createdAt: 1700000000,
     22     identifier: 'listing',
     23     href:
     24       '/products/' +
     25       encodeProductReference({ kind: 30402, pubkey, identifier: 'listing' }),
     26     title: '<script>Carrots</script>',
     27     summary: 'Seller summary',
     28     content: 'Text',
     29     location: 'Public area',
     30     price: {
     31       amount: '9007199254740993.123456789' as ListingView['price']['amount'],
     32       currency: 'CAD' as ListingView['price']['currency'],
     33       unit: 'kg'
     34     },
     35     quantity: null,
     36     publisher: {
     37       pubkey,
     38       label: '<img src=https://tracking.example>',
     39       assertedName: true
     40     },
     41     lastKnown: true,
     42     coverage: 'partial'
     43   };
     44 }
     45 describe('truthful search rows and persistent source notices', () => {
     46   it('renders advertised decimal/unit/area/unknown quantity and asserted publisher as text', () => {
     47     const value = listing(),
     48       html = render(ListingRow, { props: { listing: value } }).body;
     49     expect(html).toContain('9007199254740993.123456789');
     50     expect(html).toContain('CAD');
     51     expect(html).toContain('kg');
     52     expect(html).toContain('Public area');
     53     expect(html).toContain('Advertised quantity not specified');
     54     expect(html).toContain(value.publisher.pubkey);
     55     expect(html).toContain('&lt;script>');
     56     expect(html).toContain('&lt;img');
     57     expect(html).not.toMatch(/<script|<img|onclick|certified/);
     58     expect(html).toContain('href="' + value.href + '"');
     59     expect(html).toContain('<details');
     60   });
     61   it('renders supplied quantity without calculating a comparison price or inventing stock', () => {
     62     const value = {
     63       ...listing(),
     64       quantity: {
     65         amount: '20' as NonNullable<ListingView['quantity']>['amount'],
     66         unit: 'kg' as const
     67       }
     68     };
     69     const html = render(ListingRow, { props: { listing: value } }).body;
     70     expect(html).toMatch(/20\s+kg/);
     71     expect(html).not.toContain('not specified');
     72   });
     73   it('keeps failed-source uncertainty visible outside its details and separates unavailable from bounded empty', () => {
     74     const html = render(SourceStatus, {
     75       props: { refresh: 'partial', gap: false, scopes: [] }
     76     }).body;
     77     expect(html).toContain('These results may be incomplete.');
     78     expect(html.indexOf('may be incomplete')).toBeLessThan(
     79       html.indexOf('<details')
     80     );
     81     const unavailable = render(SourceStatus, {
     82       props: { refresh: 'unavailable', gap: false, scopes: [] }
     83     }).body;
     84     expect(unavailable).toContain('Search sources are unavailable.');
     85     expect(unavailable).not.toContain('No matches');
     86     const gap = render(SourceStatus, {
     87       props: { refresh: 'partial', gap: true, scopes: [] }
     88     }).body;
     89     expect(gap).toContain('same timestamp');
     90     expect(gap).not.toContain('complete search');
     91   });
     92 });
     93 
     94 it('does not invent a source failure for cancelled, deadline or capped work', () => {
     95   for (const refresh of ['cancelled', 'deadline', 'limit', 'error'] as const) {
     96     const html = render(SourceStatus, {
     97       props: { refresh, gap: false, scopes: [] }
     98     }).body;
     99     expect(html).toContain('These results may be incomplete.');
    100     expect(html).not.toContain('One source did not respond.');
    101   }
    102 });
    103 
    104 it('renders an admitted numeric timestamp beyond Date range without crashing or changing it', () => {
    105   const value = { ...listing(), createdAt: Number.MAX_SAFE_INTEGER };
    106   const html = render(ListingRow, { props: { listing: value } }).body;
    107   expect(html).toContain(String(value.createdAt));
    108 });
    109 
    110 const mounted = vi.hoisted<{
    111   callbacks: (() => void | (() => void))[];
    112   context: unknown;
    113 }>(() => ({ callbacks: [], context: undefined }));
    114 vi.mock('svelte', async (original) => ({
    115   ...(await original<typeof import('svelte')>()),
    116   getContext: () => mounted.context,
    117   onMount: (callback: () => void | (() => void)) => {
    118     mounted.callbacks.push(callback);
    119   }
    120 }));
    121 vi.mock('$app/state', () => ({
    122   page: { url: new URL('https://harvestcircle.example/search?q=carrots') }
    123 }));
    124 vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
    125 describe('actual search route mounted initialization', () => {
    126   let runtime: typeof import('../../../src/lib/runtime/public-runtime.ts');
    127   let context: ReturnType<typeof runtime.createPublicRuntimeContext>;
    128   let cleanup: void | (() => void);
    129   const unhandled: unknown[] = [];
    130   const record = (error: unknown) => {
    131     unhandled.push(error);
    132   };
    133   beforeEach(async () => {
    134     vi.resetModules();
    135     vi.stubGlobal('window', {});
    136     mounted.callbacks.length = 0;
    137     unhandled.length = 0;
    138     cleanup = undefined;
    139     runtime = await import('../../../src/lib/runtime/public-runtime.ts');
    140     context = runtime.createPublicRuntimeContext();
    141     mounted.context = context;
    142     process.on('unhandledRejection', record);
    143   });
    144   afterEach(() => {
    145     if (typeof cleanup === 'function') cleanup();
    146     runtime.closePublicRuntime(context);
    147     process.off('unhandledRejection', record);
    148     vi.restoreAllMocks();
    149     vi.unstubAllGlobals();
    150   });
    151   async function mountCallback() {
    152     const { render } = await import('svelte/server');
    153     const { default: SearchPage } =
    154       await import('../../../src/routes/search/+page.svelte');
    155     const html = render(SearchPage, {
    156       context: new Map([[runtime.PUBLIC_RUNTIME_CONTEXT, context]])
    157     }).body;
    158     expect(html).toContain('Search sources are unavailable.');
    159     expect(mounted.callbacks.length).toBeGreaterThan(0);
    160     cleanup = mounted.callbacks[0]();
    161   }
    162   const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
    163   it('handles a genuine unavailable public projection without requests, timers or an unhandled rejection', async () => {
    164     runtime.mountPublicRuntime(context);
    165     const { getPublicStore, closePublicStore } =
    166       await import('../../../src/lib/nostr/public-store.ts');
    167     const store = getPublicStore();
    168     expect(store).toBeDefined();
    169     closePublicStore(store!);
    170     const { RelayPool } = await import('applesauce-relay/pool');
    171     const request = vi.spyOn(RelayPool.prototype, 'req');
    172     const timer = vi.spyOn(globalThis, 'setTimeout');
    173     const create = vi.spyOn(runtime, 'createPublicView');
    174     await mountCallback();
    175     await settle();
    176     expect(create).toHaveBeenCalledTimes(1);
    177     expect(create.mock.results[0].value).toMatchObject({
    178       message: 'public_projection_unavailable'
    179     });
    180     expect(request).not.toHaveBeenCalled();
    181     expect(timer).not.toHaveBeenCalled();
    182     expect(unhandled).toEqual([]);
    183   });
    184   it('disposes exactly the partially created view when search-owner construction fails', async () => {
    185     const shared = runtime.mountPublicRuntime(context)!;
    186     const other = runtime.createPublicView(shared);
    187     const views = await import('../../../src/lib/catalog/search-view.ts');
    188     vi.spyOn(views, 'createSearchView').mockImplementation(() => {
    189       throw Error('fixture_search_owner_failed');
    190     });
    191     const create = vi.spyOn(runtime, 'createPublicView');
    192     const dispose = vi.spyOn(runtime, 'disposePublicView');
    193     await mountCallback();
    194     await settle();
    195     expect(create).toHaveBeenCalledTimes(1);
    196     expect(dispose).toHaveBeenCalledExactlyOnceWith(
    197       create.mock.results[0].value
    198     );
    199     expect(runtime.publicViewProjectionAvailable(other)).toBe(true);
    200     expect(unhandled).toEqual([]);
    201     runtime.disposePublicView(other);
    202   });
    203   it('handles rejected readiness without acquiring a view', async () => {
    204     vi.spyOn(runtime, 'publicRuntimeReady').mockRejectedValue(
    205       Error('fixture_ready_failed')
    206     );
    207     const create = vi.spyOn(runtime, 'createPublicView');
    208     await mountCallback();
    209     await settle();
    210     expect(create).not.toHaveBeenCalled();
    211     expect(unhandled).toEqual([]);
    212   });
    213   it('keeps late genuine readiness after page disposal inert', async () => {
    214     const create = vi.spyOn(runtime, 'createPublicView');
    215     await mountCallback();
    216     expect(typeof cleanup).toBe('function');
    217     if (typeof cleanup === 'function') cleanup();
    218     cleanup = undefined;
    219     runtime.mountPublicRuntime(context);
    220     await settle();
    221     expect(create).not.toHaveBeenCalled();
    222     expect(unhandled).toEqual([]);
    223   });
    224 });