freeCodeCamp/api-server/server/utils/in-memory-cache.test.js

69 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-02-04 12:34:44 +00:00
/* global describe beforeEach expect it */
2018-12-01 11:21:40 +00:00
import inMemoryCache from './in-memory-cache';
import sinon from 'sinon';
2018-12-01 11:21:40 +00:00
describe('InMemoryCache', () => {
let reportErrorStub;
2018-12-01 11:21:40 +00:00
const theAnswer = 42;
const before = 'before';
const after = 'after';
const emptyCacheValue = null;
beforeEach(() => {
reportErrorStub = sinon.spy();
});
it('throws if no report function is passed as a second argument', () => {
expect(() => inMemoryCache(null)).toThrowError(
'No reportError function specified for this in-memory-cache'
);
});
2018-12-01 11:21:40 +00:00
describe('get', () => {
2018-12-01 11:21:40 +00:00
it('returns an initial value', () => {
const cache = inMemoryCache(theAnswer, reportErrorStub);
2018-12-01 11:21:40 +00:00
expect(cache.get()).toBe(theAnswer);
});
});
describe('update', () => {
it('updates the cached value', () => {
const cache = inMemoryCache(before, reportErrorStub);
2018-12-01 11:21:40 +00:00
cache.update(() => after);
expect(cache.get()).toBe(after);
});
it('can handle promises correctly', done => {
const cache = inMemoryCache(before, reportErrorStub);
const promisedUpdate = () => new Promise(resolve => resolve(after));
2018-12-03 17:45:34 +00:00
cache.update(promisedUpdate).then(() => {
2018-12-01 11:21:40 +00:00
expect(cache.get()).toBe(after);
done();
});
});
it('reports errors thrown from the update function', () => {
const reportErrorStub = sinon.spy();
const cache = inMemoryCache(before, reportErrorStub);
const updateError = new Error('An update error');
const updateThatThrows = () => {
throw updateError;
};
cache.update(updateThatThrows);
expect(reportErrorStub.calledWith(updateError)).toBe(true);
});
2018-12-01 11:21:40 +00:00
});
describe('clear', () => {
it('clears the cache', () => {
expect.assertions(2);
const cache = inMemoryCache(theAnswer, reportErrorStub);
2018-12-01 11:21:40 +00:00
expect(cache.get()).toBe(theAnswer);
cache.clear();
expect(cache.get()).toBe(emptyCacheValue);
});
});
});