|
| 1 | +// env jest |
| 2 | + |
| 3 | +const cache = require('./cache'); |
| 4 | + |
| 5 | +describe('cache()', () => { |
| 6 | + const parent = { id: 1 }; |
| 7 | + const args = { name: 'hello' }; |
| 8 | + let cacheMock; |
| 9 | + |
| 10 | + beforeAll(() => { |
| 11 | + cacheMock = { |
| 12 | + get: jest.fn(() => Promise.resolve()), |
| 13 | + }; |
| 14 | + }); |
| 15 | + |
| 16 | + describe('hashing', () => { |
| 17 | + it('hashes the root and arguments consistently', () => { |
| 18 | + const resolver = cache(() => {}); |
| 19 | + |
| 20 | + resolver(parent, args, { resolverCache: cacheMock }); |
| 21 | + resolver(parent, args, { resolverCache: cacheMock }); |
| 22 | + |
| 23 | + const call1Args = cacheMock.get.mock.calls[0][0]; |
| 24 | + const call2Args = cacheMock.get.mock.calls[1][0]; |
| 25 | + |
| 26 | + expect(call1Args).toEqual(call2Args); |
| 27 | + }); |
| 28 | + }); |
| 29 | + |
| 30 | + describe('cache retrieval', () => { |
| 31 | + const cachedValue = 'cached'; |
| 32 | + const uncachedValue = 'uncached'; |
| 33 | + const resolver = cache(() => uncachedValue); |
| 34 | + |
| 35 | + it('returns cached value if the cache returns a value', () => { |
| 36 | + cacheMock.get = jest.fn(() => Promise.resolve(cachedValue)); |
| 37 | + |
| 38 | + expect.assertions(1); |
| 39 | + |
| 40 | + resolver(parent, args, { resolverCache: cacheMock }).then(actual => { |
| 41 | + expect(actual).toEqual(cachedValue); |
| 42 | + }); |
| 43 | + }); |
| 44 | + |
| 45 | + it('returns uncached value if the cache returns undefined', () => { |
| 46 | + cacheMock.get = jest.fn(() => Promise.resolve(undefined)); |
| 47 | + |
| 48 | + expect.assertions(1); |
| 49 | + |
| 50 | + resolver(parent, args, { resolverCache: cacheMock }).then(actual => { |
| 51 | + expect(actual).toEqual(uncachedValue); |
| 52 | + }); |
| 53 | + }); |
| 54 | + }); |
| 55 | +}); |
0 commit comments