diff --git a/packages/tron-wallet-snap/src/caching/useCache.test.ts b/packages/tron-wallet-snap/src/caching/useCache.test.ts index 456f8a2b9..d026e6b58 100644 --- a/packages/tron-wallet-snap/src/caching/useCache.test.ts +++ b/packages/tron-wallet-snap/src/caching/useCache.test.ts @@ -3,6 +3,79 @@ import type { ICache } from './ICache'; import { useCache } from './useCache'; import type { CacheOptions } from './useCache'; +type WithUseCacheCallback = (payload: { + cachedTestFunction: () => Promise; + cachedTestFunctionWithArgs: (arg1: string, arg2: number) => Promise; + cachedTestFunctionWithComplexArgs: (obj: { + name: string; + age: number; + }) => Promise; +}) => void | Promise; + +/** + * Wraps tests for `useCache` by creating fresh cached functions backed by a + * mock cache. + * + * @param testFn - The test body receiving the cached functions. + * @returns A promise that resolves when the test function completes. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +async function withUseCache(testFn: WithUseCacheCallback): Promise { + // Reset mocks for each test + const actualExecutionSpy = jest + .fn, Serializable[]>() + .mockResolvedValue('test'); + + // Create a mock cache + const cache = { + get: jest.fn().mockResolvedValue(undefined), + set: jest.fn().mockResolvedValue(undefined), + } as unknown as ICache; + + // Define common cache options + const cacheOptions = { + ttlMilliseconds: 1000, + functionName: 'testFunction', + }; + + // Define original functions + const testFunction = async (): Promise => actualExecutionSpy(); + const testFunctionWithArgs = async ( + arg1: string, + arg2: number, + ): Promise => actualExecutionSpy(arg1, arg2); + const testFunctionWithComplexArgs = async (obj: { + name: string; + age: number; + }): Promise => actualExecutionSpy(obj); + + // Create cached versions + const cachedTestFunction = useCache(testFunction, cache, { + ...cacheOptions, + functionName: 'testFunction', + }); + + const cachedTestFunctionWithArgs = useCache(testFunctionWithArgs, cache, { + ...cacheOptions, + functionName: 'testFunctionWithArgs', + }); + + const cachedTestFunctionWithComplexArgs = useCache( + testFunctionWithComplexArgs, + cache, + { + ...cacheOptions, + functionName: 'testFunctionWithComplexArgs', + }, + ); + + await testFn({ + cachedTestFunction, + cachedTestFunctionWithArgs, + cachedTestFunctionWithComplexArgs, + }); +} + describe('useCache', () => { // Spy to check if the original function was executed or not let actualExecutionSpy: jest.Mock;