/ typescript

Mock memory-cache in TypeScript with Jest

Level - Intermediate. Read Time ~ <2 minutes.

Maybe it's just me, but when I have break from Jest I find getting to grips with the syping/mocking to be a bit fiddly until the penny drops. Here is a very short post on how to mock the memory-cache npm package with Jest.

I'll let the below code speak for itself. I am attempting to test the get function of the in-memory cache library.

import MemoryCache from 'memory-cache';

export interface CacheServiceInterface {
  get(key: string): any;
  set(key: string, value: any, ttl?: number): boolean;
  delete(key: string): boolean;
}

export default class CacheService implements CacheServiceInterface {
  get(key: string): any {
    if (!key) {
      return undefined;
    }

    const cacheValue = MemoryCache.get(key);

    return cacheValue ? JSON.parse(cacheValue) : undefined;
  }

  set(key: string, value: any, ttl = 432000000): boolean {
    if (key && value) {
      MemoryCache.put(key, JSON.stringify(value), ttl);

      return true;
    }

    return false;
  }

  delete(key: string): boolean {
    if (key) {
      MemoryCache.del(key);

      return true;
    }

    return false;
  }
}

import CacheService from '../../src/services/cacheService';
import MemoryCache from 'memory-cache';

describe('CacheService', () => {
    test('should call memCache.get as key is set', () => {
        const returnValue = {id: 1};
        MemoryCache.get = jest.fn(() => JSON.stringify(returnValue));

        const cacheService = new CacheService();
        const cacheKey = 'myCacheKey';
        const cachedValue = cacheService.get(cacheKey);

        expect(cachedValue).toEqual(returnValue);
        expect(MemoryCache.get).toBeCalledTimes(1);
    });

    test('should not call memCache.get as key is not set', () => {
        MemoryCache.get = jest.fn();

        const cacheService = new CacheService();
        const cacheKey = '';
        const cachedValue = cacheService.get(cacheKey);

        expect(cachedValue).toEqual(undefined);
        expect(MemoryCache.get).toBeCalledTimes(0);
    });
});

Any comments drop them below and I'll try my best to reply.