|
| 1 | +import { readFileSync } from "node:fs"; |
| 2 | + |
| 3 | +import mockFs from "mock-fs"; |
| 4 | +import { afterEach, describe, expect, test } from "vitest"; |
| 5 | + |
| 6 | +import { patchCacheInterceptor, patchCacheInterceptorSource } from "./cache-interceptor.js"; |
| 7 | + |
| 8 | +const cacheInterceptorSource = ` |
| 9 | +function getBodyForAppRouter(event, cachedValue) { |
| 10 | + const segmentHeader = \`\${event.headers[NEXT_SEGMENT_PREFETCH_HEADER]}\`; |
| 11 | + const isSegmentResponse = |
| 12 | + Boolean(segmentHeader) && |
| 13 | + segmentHeader in (cachedValue.segmentData || {}) && |
| 14 | + !NextConfig.experimental?.prefetchInlining; |
| 15 | + const body = isSegmentResponse |
| 16 | + ? cachedValue.segmentData[segmentHeader] |
| 17 | + : cachedValue.rsc; |
| 18 | + return { body }; |
| 19 | +} |
| 20 | +`; |
| 21 | + |
| 22 | +describe("patchCacheInterceptor", () => { |
| 23 | + afterEach(() => mockFs.restore()); |
| 24 | + |
| 25 | + test("patches the generated middleware", () => { |
| 26 | + const outputDir = "/app/.open-next"; |
| 27 | + const middlewarePath = `${outputDir}/middleware/handler.mjs`; |
| 28 | + mockFs({ [middlewarePath]: cacheInterceptorSource }); |
| 29 | + |
| 30 | + patchCacheInterceptor({ outputDir }); |
| 31 | + |
| 32 | + expect(readFileSync(middlewarePath, "utf8")).not.toContain("!NextConfig.experimental?.prefetchInlining"); |
| 33 | + }); |
| 34 | + |
| 35 | + test("serves cached segment data when prefetch inlining is enabled", () => { |
| 36 | + const patchedSource = patchCacheInterceptorSource(cacheInterceptorSource); |
| 37 | + |
| 38 | + expect(patchedSource).toContain( |
| 39 | + "Boolean(segmentHeader) && segmentHeader in (cachedValue.segmentData || {})" |
| 40 | + ); |
| 41 | + expect(patchedSource).not.toContain("!NextConfig.experimental?.prefetchInlining"); |
| 42 | + }); |
| 43 | + |
| 44 | + test("fails when the upstream cache interceptor no longer matches", () => { |
| 45 | + expect(() => patchCacheInterceptorSource("const isSegmentResponse = false;")).toThrow( |
| 46 | + "Failed to patch the OpenNext cache interceptor" |
| 47 | + ); |
| 48 | + }); |
| 49 | +}); |
0 commit comments