From ee13f13ee366a73d67ef76f36f7ee3e39660da0a Mon Sep 17 00:00:00 2001 From: Xiphe Date: Mon, 24 Oct 2022 13:12:55 +0200 Subject: [PATCH] refactor: cover last 3 branches with tests --- src/assertCacheEntry.ts | 18 +++++++++--------- src/cachified.spec.ts | 11 ++++++++++- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/assertCacheEntry.ts b/src/assertCacheEntry.ts index 286d50f..55aa175 100644 --- a/src/assertCacheEntry.ts +++ b/src/assertCacheEntry.ts @@ -1,5 +1,9 @@ import type { CacheMetadata } from './common'; +export function logKey(key?: string) { + return key ? `for ${key} ` : ''; +} + export function assertCacheEntry( entry: unknown, key?: string, @@ -9,9 +13,9 @@ export function assertCacheEntry( } { if (!isRecord(entry)) { throw new Error( - `Cache entry ${ - key ? `for ${key} ` : '' - }is not a cache entry object, it's a ${typeof entry}`, + `Cache entry ${logKey( + key, + )}is not a cache entry object, it's a ${typeof entry}`, ); } if ( @@ -21,17 +25,13 @@ export function assertCacheEntry( (entry.metadata.swr != null && typeof entry.metadata.swr !== 'number') ) { throw new Error( - `Cache entry ${ - key ? `for ${key} ` : '' - }does not have valid metadata property`, + `Cache entry ${logKey(key)}does not have valid metadata property`, ); } if (!('value' in entry)) { throw new Error( - `Cache entry for ${ - key ? `for ${key} ` : '' - }does not have a value property`, + `Cache entry for ${logKey(key)}does not have a value property`, ); } } diff --git a/src/cachified.spec.ts b/src/cachified.spec.ts index b48a152..30e4bca 100644 --- a/src/cachified.spec.ts +++ b/src/cachified.spec.ts @@ -18,6 +18,7 @@ import { totalTtl, } from './index'; import { Deferred } from './createBatch'; +import { logKey } from './assertCacheEntry'; jest.mock('./index', () => { if (process.version.startsWith('v18')) { @@ -1249,7 +1250,9 @@ describe('cachified', () => { (cb as Function)(new Error('Nope2'), null); return false; }); - expect(cache.delete('test-0')).rejects.toThrowErrorMatchingInlineSnapshot(`"Nope2"`); + expect(cache.delete('test-0')).rejects.toThrowErrorMatchingInlineSnapshot( + `"Nope2"`, + ); // handle corrupt cache await new Promise((res) => redis.set('test-3', '{{{', res)); @@ -1589,3 +1592,9 @@ describe('totalTtl helper', () => { expect(totalTtl({ createdTime: 0, swr: 5 })).toBe(5); }); }); + +describe('internal logKey helper', () => { + it('falls back to empty string, when no key given', () => { + expect(logKey()).toBe(''); + }); +});