-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathfetch-handler.test.ts
301 lines (257 loc) · 10 KB
/
fetch-handler.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import { load } from 'cheerio'
import { getLogger } from 'lambda-local'
import { HttpResponse, http, passthrough } from 'msw'
import { setupServer } from 'msw/node'
import { v4 } from 'uuid'
import { afterAll, beforeAll, beforeEach, expect, test, vi } from 'vitest'
import { type FixtureTestContext } from '../utils/contexts.js'
import { createFixture, invokeFunction, runPlugin, runPluginStep } from '../utils/fixture.js'
import { generateRandomObjectID, startMockBlobStore } from '../utils/helpers.js'
// Disable the verbose logging of the lambda-local runtime
getLogger().level = 'alert'
let handlerCalled = 0
let server: ReturnType<typeof setupServer>
beforeAll(() => {
// Enable API mocking before tests.
// mock just https://api.tvmaze.com/shows/:params which is used by tested routes
// and passthrough everything else
server = setupServer(
http.get('https://api.tvmaze.com/shows/:params', () => {
handlerCalled++
const date = new Date().toISOString()
return HttpResponse.json(
{
id: '1',
name: 'Fake response',
date,
},
{
headers: {
'cache-control': 'public, max-age=10000',
},
},
)
}),
http.all(/.*/, () => passthrough()),
)
server.listen()
})
afterAll(() => {
// Disable API mocking after the tests are done.
server.close()
})
beforeEach<FixtureTestContext>(async (ctx) => {
// set for each test a new deployID and siteID
ctx.deployID = generateRandomObjectID()
ctx.siteID = v4()
vi.stubEnv('SITE_ID', ctx.siteID)
vi.stubEnv('DEPLOY_ID', ctx.deployID)
// hide debug logs in tests
// vi.spyOn(console, 'debug').mockImplementation(() => {})
await startMockBlobStore(ctx)
handlerCalled = 0
})
test<FixtureTestContext>('if the fetch call is cached correctly (force-dynamic page)', async (ctx) => {
await createFixture('revalidate-fetch', ctx)
await runPluginStep(ctx, 'onPreBuild')
await runPlugin(ctx)
handlerCalled = 0
const post1 = await invokeFunction(ctx, {
url: 'dynamic-posts/1',
})
// allow for background regeneration to happen
await new Promise<void>((resolve) => setTimeout(resolve, 500))
const post1FetchDate = load(post1.body)('[data-testid="date-from-response"]').text()
const post1Name = load(post1.body)('[data-testid="name"]').text()
expect(
handlerCalled,
'API should be hit as fetch did NOT happen during build for dynamic page',
).toBeGreaterThan(0)
expect(post1.statusCode).toBe(200)
expect(post1Name).toBe('Fake response')
expect(post1.headers, 'the page should not be cacheable').toEqual(
expect.not.objectContaining({
'cache-status': expect.any(String),
}),
)
handlerCalled = 0
const post2 = await invokeFunction(ctx, {
url: 'dynamic-posts/1',
})
// allow for any potential background regeneration to happen
await new Promise<void>((resolve) => setTimeout(resolve, 500))
const post2FetchDate = load(post2.body)('[data-testid="date-from-response"]').text()
const post2Name = load(post2.body)('[data-testid="name"]').text()
expect(handlerCalled, 'API should NOT be hit as fetch-cache is still fresh').toBe(0)
expect(post2FetchDate, 'Cached fetch response should be used').toBe(post1FetchDate)
expect(post2.statusCode).toBe(200)
expect(post2Name).toBe('Fake response')
expect(post2.headers, 'the page should not be cacheable').toEqual(
expect.not.objectContaining({
'cache-status': expect.any(String),
}),
)
// make fetch-cache stale
await new Promise<void>((resolve) => setTimeout(resolve, 7_000))
handlerCalled = 0
const post3 = await invokeFunction(ctx, {
url: 'dynamic-posts/1',
})
// allow for any potential background regeneration to happen
await new Promise<void>((resolve) => setTimeout(resolve, 500))
const post3FetchDate = load(post3.body)('[data-testid="date-from-response"]').text()
const post3Name = load(post3.body)('[data-testid="name"]').text()
// note here that we are testing if API was called it least once and not that it was
// hit exactly once - this is because of Next.js quirk that seems to cause multiple
// fetch calls being made for single request
// https://github.com/vercel/next.js/issues/44655
expect(
handlerCalled,
'API should be hit as fetch did go stale and should be revalidated',
).toBeGreaterThan(0)
expect(
post3FetchDate,
'Cached fetch response should be used (revalidation happen in background)',
).toBe(post1FetchDate)
expect(post3.statusCode).toBe(200)
expect(post3Name).toBe('Fake response')
expect(post3.headers, 'the page should not be cacheable').toEqual(
expect.not.objectContaining({
'cache-status': expect.any(String),
}),
)
handlerCalled = 0
const post4 = await invokeFunction(ctx, {
url: 'dynamic-posts/1',
})
// allow for any potential background regeneration to happen
await new Promise<void>((resolve) => setTimeout(resolve, 500))
const post4FetchDate = load(post4.body)('[data-testid="date-from-response"]').text()
const post4Name = load(post4.body)('[data-testid="name"]').text()
expect(
handlerCalled,
'API should NOT be hit as fetch-cache is still fresh after being revalidated in background by previous request',
).toBe(0)
expect(
post4FetchDate,
'Response cached in background by previous request should be used',
).not.toBe(post3FetchDate)
expect(post4.statusCode).toBe(200)
expect(post4Name).toBe('Fake response')
expect(post4.headers, 'the page should not be cacheable').toEqual(
expect.not.objectContaining({
'cache-status': expect.any(String),
}),
)
})
test<FixtureTestContext>('if the fetch call is cached correctly (cached page response)', async (ctx) => {
await createFixture('revalidate-fetch', ctx)
await runPluginStep(ctx, 'onPreBuild')
await runPlugin(ctx)
handlerCalled = 0
const post1 = await invokeFunction(ctx, {
url: 'posts/1',
})
// allow for background regeneration to happen
await new Promise<void>((resolve) => setTimeout(resolve, 500))
const post1FetchDate = load(post1.body)('[data-testid="date-from-response"]').text()
const post1Name = load(post1.body)('[data-testid="name"]').text()
expect(handlerCalled, 'API should be hit as page was revalidated in background').toBeGreaterThan(
0,
)
expect(post1.statusCode).toBe(200)
expect(post1Name, 'a stale page served with swr').not.toBe('Fake response')
expect(post1.headers, 'a stale page served with swr').toEqual(
expect.objectContaining({
'cache-status': '"Next.js"; hit; fwd=stale',
'netlify-cdn-cache-control': 'public, max-age=0, must-revalidate, durable',
}),
)
handlerCalled = 0
const post2 = await invokeFunction(ctx, {
url: 'posts/1',
})
// allow for any potential background regeneration to happen
await new Promise<void>((resolve) => setTimeout(resolve, 500))
const post2FetchDate = load(post2.body)('[data-testid="date-from-response"]').text()
const post2Name = load(post2.body)('[data-testid="name"]').text()
expect(
handlerCalled,
'API should NOT be hit as fetch-cache is still fresh after being revalidated in background by previous request',
).toBe(0)
expect(
post2FetchDate,
'Response cached after being revalidated in background should be now used',
).not.toBe(post1FetchDate)
expect(post2.statusCode).toBe(200)
expect(
post2Name,
'Response cached after being revalidated in background should be now used',
).toBe('Fake response')
expect(
post2.headers,
'Still fresh response after being regenerated in background by previous request',
).toEqual(
expect.objectContaining({
'cache-status': '"Next.js"; hit',
'netlify-cdn-cache-control': 's-maxage=5, stale-while-revalidate=31536000, durable',
}),
)
// make response and fetch-cache stale
await new Promise<void>((resolve) => setTimeout(resolve, 7_000))
handlerCalled = 0
const post3 = await invokeFunction(ctx, {
url: 'posts/1',
})
// allow for any potential background regeneration to happen
await new Promise<void>((resolve) => setTimeout(resolve, 500))
const post3FetchDate = load(post3.body)('[data-testid="date-from-response"]').text()
const post3Name = load(post3.body)('[data-testid="name"]').text()
// note here that we are testing if API was called it least once and not that it was
// hit exactly once - this is because of Next.js quirk that seems to cause multiple
// fetch calls being made for single request
// https://github.com/vercel/next.js/issues/44655
expect(
handlerCalled,
'API should be hit as fetch did go stale and should be revalidated',
).toBeGreaterThan(0)
expect(
post3FetchDate,
'Cached fetch response should be used (revalidation happen in background)',
).toBe(post2FetchDate)
expect(post3.statusCode).toBe(200)
expect(post3Name).toBe('Fake response')
expect(post3.headers, 'a stale page served with swr').toEqual(
expect.objectContaining({
'cache-status': '"Next.js"; hit; fwd=stale',
'netlify-cdn-cache-control': 'public, max-age=0, must-revalidate, durable',
}),
)
handlerCalled = 0
const post4 = await invokeFunction(ctx, {
url: 'posts/1',
})
// allow for any potential background regeneration to happen
await new Promise<void>((resolve) => setTimeout(resolve, 500))
const post4FetchDate = load(post4.body)('[data-testid="date-from-response"]').text()
const post4Name = load(post4.body)('[data-testid="name"]').text()
expect(
handlerCalled,
'API should NOT be hit as fetch-cache is still fresh after being revalidated in background by previous request',
).toBe(0)
expect(
post4FetchDate,
'Response cached in background by previous request should be used',
).not.toBe(post3FetchDate)
expect(post4.statusCode).toBe(200)
expect(post4Name).toBe('Fake response')
expect(
post4.headers,
'Still fresh response after being regenerated in background by previous request',
).toEqual(
expect.objectContaining({
'cache-status': '"Next.js"; hit',
'netlify-cdn-cache-control': 's-maxage=5, stale-while-revalidate=31536000, durable',
}),
)
})