import { getHistoryCompletionItems, readHistory, saveHistory } from '../history'; describe('LogQL query history', () => { const historyKey = 'logql-history-test'; beforeEach(() => { window.localStorage.clear(); }); it('does not read or write history without a key', () => { expect(saveHistory(undefined, 'service:api', 1)).toEqual([]); expect(window.localStorage.length).toBe(0); expect(readHistory(undefined)).toEqual([]); }); it('does not save blank queries', () => { expect(saveHistory(historyKey, ' ', 1)).toEqual([]); expect(window.localStorage.getItem(historyKey)).toBeNull(); }); it('increments the usage count for an existing query', () => { saveHistory(historyKey, 'service:api', 1); saveHistory(historyKey, 'service:api', 2); expect(readHistory(historyKey)).toEqual([{ query: 'service:api', usageCount: 2, lastUsedAt: 2 }]); }); it('evicts the least-used and then oldest query after 20 items', () => { for (let index = 0; index < 20; index += 1) { saveHistory(historyKey, `query-${index}`, index + 1); } saveHistory(historyKey, 'query-19', 30); saveHistory(historyKey, 'query-new', 31); const history = readHistory(historyKey); expect(history).toHaveLength(20); expect(history.find((item) => item.query === 'query-0')).toBeUndefined(); expect(history.find((item) => item.query === 'query-19')?.usageCount).toBe(2); }); it('returns only the ten most-used records for completion', () => { for (let index = 0; index < 12; index += 1) { for (let count = 0; count <= index; count += 1) { saveHistory(historyKey, `query-${index}`, index * 100 + count); } } const completions = getHistoryCompletionItems(historyKey); expect(completions).toHaveLength(10); expect(completions[0].query).toBe('query-11'); expect(completions[9].query).toBe('query-2'); }); it('silently ignores invalid cached data', () => { window.localStorage.setItem(historyKey, '{not json'); expect(readHistory(historyKey)).toEqual([]); expect(() => saveHistory(historyKey, 'service:api', 1)).not.toThrow(); }); it('silently handles unavailable localStorage', () => { const getItem = jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new Error('unavailable'); }); const setItem = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('unavailable'); }); expect(() => saveHistory(historyKey, 'service:api', 1)).not.toThrow(); getItem.mockRestore(); setItem.mockRestore(); }); });