From 60de5246910486cdfaf5dc23b19668cdfd5892e6 Mon Sep 17 00:00:00 2001 From: yuhengshs <94558971+yuhengshs@users.noreply.github.com> Date: Wed, 16 Oct 2024 11:27:00 -0700 Subject: [PATCH] fix(core): fixed cache.clear() not working as expected (#13926) * fix: fixed cache.clear() not working as epected * fix: removed mockResolve function in unit test for cache clear * feat: update unit test to use real implementation instead of mockValues --- .../Cache/StorageCacheCommon.test.ts | 19 ++++++++++++------- packages/core/src/Cache/StorageCacheCommon.ts | 3 ++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/core/__tests__/Cache/StorageCacheCommon.test.ts b/packages/core/__tests__/Cache/StorageCacheCommon.test.ts index a1488ef71e9..44e018a28a9 100644 --- a/packages/core/__tests__/Cache/StorageCacheCommon.test.ts +++ b/packages/core/__tests__/Cache/StorageCacheCommon.test.ts @@ -3,6 +3,7 @@ import { defaultConfig } from '../../src/Cache/constants'; import { StorageCacheCommon } from '../../src/Cache/StorageCacheCommon'; import { KeyValueStorageInterface } from '../../src/types'; import { ConsoleLogger } from '../../src/Logger'; +import { StorageCache } from '../../src/Cache/StorageCache'; import { getByteLength, getCurrentSizeKey, @@ -584,16 +585,20 @@ describe('StorageCacheCommon', () => { }); describe('clear()', () => { - const cache = getStorageCache(config); + const cache = new StorageCache(config); it('clears the cache, including the currentSizeKey', async () => { - mockGetAllCacheKeys.mockReturnValue([ - currentSizeKey, - `${keyPrefix}some-key`, - ]); + await cache.setItem('key1', 'value1'); + await cache.setItem('key2', 'value2'); + + expect(await cache.getItem('key1')).toBe('value1'); + expect(await cache.getItem('key2')).toBe('value2'); + await cache.clear(); - expect(loggerSpy.debug).toHaveBeenCalledWith('Clear Cache'); - expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledTimes(2); + + expect(await cache.getItem('key1')).toBeNull(); + expect(await cache.getItem('key2')).toBeNull(); + expect(await cache.getCurrentCacheSize()).toBe(0); }); }); diff --git a/packages/core/src/Cache/StorageCacheCommon.ts b/packages/core/src/Cache/StorageCacheCommon.ts index 561c469330b..24ffa33e55c 100644 --- a/packages/core/src/Cache/StorageCacheCommon.ts +++ b/packages/core/src/Cache/StorageCacheCommon.ts @@ -588,7 +588,8 @@ export abstract class StorageCacheCommon { try { const keys = await this.getAllKeys(); for (const key of keys) { - await this.getStorage().removeItem(key); + const prefixedKey = `${this.config.keyPrefix}${key}`; + await this.getStorage().removeItem(prefixedKey); } } catch (e) { logger.warn(`clear failed! ${e}`);