Files
gitbook/src/lib/cache/cache.test.ts
T
Samy Pessé 55d1e538d9 More resilient caching and use of KV (#222)
* Add unit tests for "race"

* Reduce to 80s

* Implement a Cloudflare KV cache

* Format

* Lint

* Fix tagging of entries in KV

* No longer use HTTP cache tags

* Simplify tags to only keep 2

* Implement a blockFallback logic

* Improve the block fallback logic

* More tests

* Start introducing a always optional signal on all cache ops

* Correctly pass signal end to end

* Fix one more case and add tests

* Fix it

* Add test for error

* Fix error handling

* Simplify even more

* Improve logs

* Improve logs / measurements

* Fix timing

* Fix read cache duration and add minor tests

* Log redis time

* Change replication logic

* Fix redis errors

* Log more

* More logs and test memory first

* Improve tracing for cache backends

* Ignore all dependencies

* Log the key in the cache low level traces
2024-03-08 09:43:30 +01:00

50 lines
1.3 KiB
TypeScript

import { Mock, beforeEach, describe, expect, it, mock } from 'bun:test';
import { CacheFunction, CacheFunctionOptions, cache } from './cache';
describe('cache', () => {
const impl = mock((arg: string) => 'test-' + arg);
let fn: CacheFunction<[string], string>;
let testId = 0;
beforeEach(() => {
impl.mockClear();
testId += 1;
fn = cache(`cache-${testId}`, async (arg: string, options: CacheFunctionOptions) => {
await new Promise((resolve) => setTimeout(resolve, 20));
return {
data: impl(arg),
};
});
});
it('should only execute once for same argument', async () => {
const result = await Promise.all([fn('a'), fn('a')]);
expect(result).toEqual(['test-a', 'test-a']);
expect(impl).toHaveBeenCalled();
expect(impl).toHaveBeenCalledTimes(1);
expect(await fn('a')).toEqual('test-a');
expect(impl).toHaveBeenCalledTimes(1);
});
it('should execute for different arguments', async () => {
const result = await Promise.all([fn('a'), fn('b')]);
expect(result).toEqual(['test-a', 'test-b']);
expect(impl).toHaveBeenCalled();
expect(impl).toHaveBeenCalledTimes(2);
expect(await fn('a')).toEqual('test-a');
expect(impl).toHaveBeenCalledTimes(2);
});
});