|
| 1 | +import NextNodeServer from 'next/dist/server/next-server'; |
| 2 | +import mockFs from 'mock-fs'; |
| 3 | +import fs from 'fs'; |
| 4 | +import { ImageOptimizerCache } from 'next/dist/server/image-optimizer'; |
| 5 | +import { injectNextImageCacheDir } from './image-cache-handler'; |
| 6 | +import { __getNextTestApp } from '../../__test-utils/utils'; |
| 7 | +import { getNextServer } from '../next-utils'; |
| 8 | + |
| 9 | +describe('Set next.js image cache dir', () => { |
| 10 | + const nextApp = __getNextTestApp(); |
| 11 | + let nextServer: NextNodeServer; |
| 12 | + |
| 13 | + const imgCacheDir = 'myImgCacheDir'; |
| 14 | + |
| 15 | + process.env.IMAGE_CACHE_DIR = `/${imgCacheDir}`; |
| 16 | + |
| 17 | + beforeAll(async () => { |
| 18 | + await nextApp.prepare(); |
| 19 | + nextServer = await getNextServer(nextApp); |
| 20 | + await injectNextImageCacheDir(nextServer, process.env.IMAGE_CACHE_DIR); |
| 21 | + }); |
| 22 | + |
| 23 | + afterEach(() => { |
| 24 | + mockFs.restore(); |
| 25 | + }); |
| 26 | + |
| 27 | + test('IncrementalCache should write to the correct image cache dir', async () => { |
| 28 | + mockFs(); |
| 29 | + |
| 30 | + // Handles next.js responseCache async fs write operation |
| 31 | + let resolveOnWriteFile: any = () => {}; |
| 32 | + const promise = new Promise((resolve) => { |
| 33 | + resolveOnWriteFile = resolve; |
| 34 | + }); |
| 35 | + |
| 36 | + fs.promises.writeFile = jest.fn(resolveOnWriteFile); |
| 37 | + |
| 38 | + const imgCache = new ImageOptimizerCache({ |
| 39 | + distDir: 'dummyValueWhichGetsReplaceByInjector', |
| 40 | + nextConfig: nextServer['nextConfig'], |
| 41 | + }); |
| 42 | + |
| 43 | + await nextServer['imageResponseCache'].get( |
| 44 | + 'foo', |
| 45 | + async () => ({ |
| 46 | + value: { |
| 47 | + kind: 'IMAGE', |
| 48 | + buffer: Buffer.from('bar', 'utf-8'), |
| 49 | + etag: 'test', |
| 50 | + extension: 'png', |
| 51 | + }, |
| 52 | + revalidate: 1337, |
| 53 | + }), |
| 54 | + { |
| 55 | + incrementalCache: imgCache, |
| 56 | + } |
| 57 | + ); |
| 58 | + |
| 59 | + await Promise.all([promise]).then(() => |
| 60 | + expect(fs.promises.writeFile).toHaveBeenCalledWith( |
| 61 | + expect.stringContaining(imgCacheDir), |
| 62 | + expect.anything() |
| 63 | + ) |
| 64 | + ); |
| 65 | + }); |
| 66 | +}); |
0 commit comments