@faststore/core 4.11.4-dev.5 → 4.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,80 +0,0 @@
1
- /**
2
- * @vitest-environment jsdom
3
- */
4
-
5
- import React from 'react'
6
- import { render } from '@testing-library/react'
7
- import { afterEach, describe, expect, it, vi } from 'vitest'
8
-
9
- const { received, capture } = vi.hoisted(() => {
10
- const received: Record<string, Record<string, unknown>> = {}
11
- const capture =
12
- (name: string) =>
13
- ({
14
- children,
15
- ...props
16
- }: Readonly<{ children?: unknown } & Record<string, unknown>>) => {
17
- received[name] = props
18
- return (children ?? null) as never
19
- }
20
- return { received, capture }
21
- })
22
-
23
- vi.mock('@faststore/ui', () => ({
24
- SearchDropdown: capture('SearchDropdown'),
25
- SearchAutoComplete: capture('SearchAutoComplete'),
26
- SearchAutoCompleteTerm: capture('SearchAutoCompleteTerm'),
27
- SearchProducts: capture('SearchProducts'),
28
- useSearch: () => ({
29
- values: { products: [], term: '', terms: [], searchId: undefined },
30
- }),
31
- }))
32
-
33
- vi.mock('src/components/search/SearchHistory', () => ({
34
- SearchHistory: capture('SearchHistory'),
35
- }))
36
-
37
- vi.mock('src/components/search/SearchTop', () => ({
38
- SearchTop: capture('SearchTop'),
39
- }))
40
-
41
- vi.mock('src/components/search/SearchProductItem', () => ({
42
- default: () => null,
43
- }))
44
-
45
- vi.mock('src/sdk/search/formatSearchPath', () => ({
46
- useFormatSearchPath: () => (args: { term: string }) => `/s?q=${args.term}`,
47
- }))
48
-
49
- import SearchDropdown from '../../../src/components/search/SearchDropdown/SearchDropdown'
50
-
51
- afterEach(() => {
52
- for (const key of Object.keys(received)) delete received[key]
53
- })
54
-
55
- describe('SearchDropdown labels', () => {
56
- it('forwards the CMS labels to each dropdown block', () => {
57
- render(
58
- <SearchDropdown
59
- sort="score_desc"
60
- loadingLabel="Carregando..."
61
- searchHistoryTitle="Histórico"
62
- searchHistoryClearLabel="Limpar histórico"
63
- searchTopTitle="Mais buscados"
64
- searchProductsTitle="Produtos sugeridos"
65
- />
66
- )
67
-
68
- expect(received.SearchDropdown).toMatchObject({
69
- loadingLabel: 'Carregando...',
70
- })
71
- expect(received.SearchHistory).toMatchObject({
72
- title: 'Histórico',
73
- clearLabel: 'Limpar histórico',
74
- })
75
- expect(received.SearchTop).toMatchObject({ title: 'Mais buscados' })
76
- expect(received.SearchProducts).toMatchObject({
77
- title: 'Produtos sugeridos',
78
- })
79
- })
80
- })
@@ -1,482 +0,0 @@
1
- import type { Server } from 'node:http'
2
- import { createServer } from 'node:http'
3
- import type { AddressInfo } from 'node:net'
4
- import { gzipSync } from 'node:zlib'
5
- import ClientCMS from '@vtex/client-cms'
6
- import type { ContentData, ContentPage } from '@vtex/client-cms'
7
- import {
8
- afterAll,
9
- afterEach,
10
- beforeAll,
11
- beforeEach,
12
- describe,
13
- expect,
14
- it,
15
- vi,
16
- } from 'vitest'
17
-
18
- import { clientCMS, cmsPageCache, getCMSPage } from '../../../src/server/cms'
19
- import {
20
- CACHE_BUST_PARAM,
21
- CACHE_BUST_WINDOW_MS,
22
- RETRY_COOLDOWN_MS,
23
- ResilientClientCMS,
24
- } from '../../../src/server/cms/ResilientClientCMS'
25
-
26
- const invalidJSON = () =>
27
- new SyntaxError('Unexpected token \u001f in JSON at position 0')
28
-
29
- const contentData = (id: string): ContentData => ({
30
- id,
31
- name: id,
32
- status: 'published',
33
- type: 'plp',
34
- sections: [],
35
- releaseId: '',
36
- })
37
-
38
- const listingPage = (
39
- page: number,
40
- count: number,
41
- totalItems: number
42
- ): ContentPage => ({
43
- data: Array.from({ length: count }, (_, i) =>
44
- contentData(`page-${page}-item-${i}`)
45
- ),
46
- hasNextPage: page * 10 < totalItems,
47
- totalItems,
48
- })
49
-
50
- describe('ResilientClientCMS', () => {
51
- // `ResilientClientCMS#fetch` delegates to the `ClientCMS` implementation,
52
- // which performs the HTTP request and parses the JSON body.
53
- let baseFetch: ReturnType<typeof vi.spyOn>
54
- let warn: ReturnType<typeof vi.spyOn>
55
-
56
- const createClient = () =>
57
- new ResilientClientCMS({
58
- tenant: 'store',
59
- workspace: 'master',
60
- builder: 'faststore',
61
- host: 'www.example.com',
62
- })
63
-
64
- const paramsOfCall = (call: number) =>
65
- baseFetch.mock.calls[call][1] as URLSearchParams | undefined
66
-
67
- beforeEach(() => {
68
- cmsPageCache.clear()
69
- baseFetch = vi.spyOn(ClientCMS.prototype, 'fetch')
70
- warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
71
- })
72
-
73
- afterEach(() => {
74
- vi.restoreAllMocks()
75
- })
76
-
77
- it('makes a single request when the response is valid', async () => {
78
- const page = listingPage(1, 3, 3)
79
- baseFetch.mockResolvedValueOnce(page)
80
-
81
- const result = await createClient().getCMSPagesByContentType('plp')
82
-
83
- expect(result).toEqual(page)
84
- expect(baseFetch).toHaveBeenCalledTimes(1)
85
- expect(paramsOfCall(0)?.has(CACHE_BUST_PARAM)).toBe(false)
86
- expect(warn).not.toHaveBeenCalled()
87
- })
88
-
89
- it('retries once bypassing the cache when the body is not valid JSON', async () => {
90
- const page = listingPage(8, 10, 100)
91
- baseFetch.mockRejectedValueOnce(invalidJSON()).mockResolvedValueOnce(page)
92
-
93
- const result = await createClient().getCMSPagesByContentType('plp', {
94
- page: 8,
95
- perPage: 10,
96
- })
97
-
98
- expect(result).toEqual(page)
99
- expect(baseFetch).toHaveBeenCalledTimes(2)
100
-
101
- expect(baseFetch.mock.calls[1][0]).toBe('plp')
102
- const retryParams = paramsOfCall(1)
103
- expect(retryParams?.get('page')).toBe('8')
104
- expect(retryParams?.get('per_page')).toBe('10')
105
- expect(retryParams?.get(CACHE_BUST_PARAM)).toMatch(/^\d+$/)
106
- // The original params are not mutated.
107
- expect(paramsOfCall(0)?.has(CACHE_BUST_PARAM)).toBe(false)
108
-
109
- expect(warn).toHaveBeenCalledTimes(1)
110
- expect(warn.mock.calls[0][0]).toContain('plp?page=8&per_page=10')
111
- })
112
-
113
- it('rejects when the retry is not valid JSON either', async () => {
114
- baseFetch
115
- .mockRejectedValueOnce(invalidJSON())
116
- .mockRejectedValueOnce(invalidJSON())
117
-
118
- await expect(
119
- createClient().getCMSPagesByContentType('plp')
120
- ).rejects.toBeInstanceOf(SyntaxError)
121
- expect(baseFetch).toHaveBeenCalledTimes(2)
122
- })
123
-
124
- it('handles the invalid-json error raised by node-fetch', async () => {
125
- const nodeFetchError = Object.assign(
126
- new Error('invalid json response body'),
127
- { type: 'invalid-json' }
128
- )
129
- const document = contentData('document')
130
- baseFetch
131
- .mockRejectedValueOnce(nodeFetchError)
132
- .mockResolvedValueOnce(document)
133
-
134
- const result = await createClient().getCMSPage({
135
- contentType: 'landingPage',
136
- documentId: 'document',
137
- versionId: 'version',
138
- })
139
-
140
- expect(result).toEqual(document)
141
- expect(baseFetch).toHaveBeenCalledTimes(2)
142
- expect(baseFetch.mock.calls[1][0]).toBe('landingPage/document')
143
- expect(paramsOfCall(1)?.get('versionId')).toBe('version')
144
- })
145
-
146
- it('passes a body that parses to null through without retrying', async () => {
147
- baseFetch.mockResolvedValueOnce(null)
148
-
149
- const result = await createClient().getCMSPagesByContentType('plp')
150
-
151
- expect(result).toBeNull()
152
- expect(baseFetch).toHaveBeenCalledTimes(1)
153
- expect(warn).not.toHaveBeenCalled()
154
- })
155
-
156
- it('adds the cache-busting param to requests without params', async () => {
157
- baseFetch
158
- .mockRejectedValueOnce(invalidJSON())
159
- .mockResolvedValueOnce({ contentTypes: [{ id: 'plp' }] })
160
-
161
- const result = await createClient().getAllContentTypeIds()
162
-
163
- expect(result).toEqual(['plp'])
164
- expect(paramsOfCall(1)?.has(CACHE_BUST_PARAM)).toBe(true)
165
- })
166
-
167
- it('does not retry other errors', async () => {
168
- const error = new Error('Error while fetching')
169
- baseFetch.mockRejectedValueOnce(error)
170
-
171
- await expect(createClient().getCMSPagesByContentType('plp')).rejects.toBe(
172
- error
173
- )
174
- expect(baseFetch).toHaveBeenCalledTimes(1)
175
- expect(warn).not.toHaveBeenCalled()
176
- })
177
-
178
- it('retries when the body cannot be decoded', async () => {
179
- // undici's error when `Content-Encoding` does not match the body bytes.
180
- const decodingError = Object.assign(new TypeError('terminated'), {
181
- cause: Object.assign(new Error('incorrect header check'), {
182
- code: 'Z_DATA_ERROR',
183
- }),
184
- })
185
- const page = listingPage(1, 1, 1)
186
- baseFetch.mockRejectedValueOnce(decodingError).mockResolvedValueOnce(page)
187
-
188
- const result = await createClient().getCMSPagesByContentType('plp')
189
-
190
- expect(result).toEqual(page)
191
- expect(baseFetch).toHaveBeenCalledTimes(2)
192
- expect(warn.mock.calls[0][0]).toContain('TypeError: Z_DATA_ERROR')
193
- })
194
-
195
- it('retries a SyntaxError created in another realm', async () => {
196
- const foreignSyntaxError = Object.assign(new Error('Unexpected token'), {
197
- name: 'SyntaxError',
198
- })
199
- const page = listingPage(1, 1, 1)
200
- baseFetch
201
- .mockRejectedValueOnce(foreignSyntaxError)
202
- .mockResolvedValueOnce(page)
203
-
204
- const result = await createClient().getCMSPagesByContentType('plp')
205
-
206
- expect(result).toEqual(page)
207
- expect(baseFetch).toHaveBeenCalledTimes(2)
208
- })
209
-
210
- it('does not retry a connection reset while reading the body', async () => {
211
- const error = Object.assign(new TypeError('terminated'), {
212
- cause: Object.assign(new Error('read ECONNRESET'), {
213
- code: 'ECONNRESET',
214
- }),
215
- })
216
- baseFetch.mockRejectedValueOnce(error)
217
-
218
- await expect(createClient().getCMSPagesByContentType('plp')).rejects.toBe(
219
- error
220
- )
221
- expect(baseFetch).toHaveBeenCalledTimes(1)
222
- })
223
-
224
- it('retries when a brotli body cannot be decoded', async () => {
225
- // Node's brotli decoder codes start with `ERR__ERROR_` (double underscore).
226
- const decodingError = Object.assign(new TypeError('terminated'), {
227
- cause: Object.assign(new Error('Decompression failed'), {
228
- code: 'ERR__ERROR_FORMAT_PADDING_1',
229
- }),
230
- })
231
- const page = listingPage(1, 1, 1)
232
- baseFetch.mockRejectedValueOnce(decodingError).mockResolvedValueOnce(page)
233
-
234
- const result = await createClient().getCMSPagesByContentType('plp')
235
-
236
- expect(result).toEqual(page)
237
- expect(baseFetch).toHaveBeenCalledTimes(2)
238
- expect(warn.mock.calls[0][0]).toContain(
239
- 'TypeError: ERR__ERROR_FORMAT_PADDING_1'
240
- )
241
- })
242
-
243
- it('reuses the cache-busting value within a window', async () => {
244
- const now = vi.spyOn(Date, 'now').mockReturnValue(10 * CACHE_BUST_WINDOW_MS)
245
- const client = createClient()
246
- const page = listingPage(1, 1, 1)
247
- baseFetch
248
- .mockRejectedValueOnce(invalidJSON())
249
- .mockResolvedValueOnce(page)
250
- .mockRejectedValueOnce(invalidJSON())
251
- .mockResolvedValueOnce(page)
252
- .mockRejectedValueOnce(invalidJSON())
253
- .mockResolvedValueOnce(page)
254
-
255
- await client.getCMSPagesByContentType('plp')
256
- now.mockReturnValue(11 * CACHE_BUST_WINDOW_MS - 1)
257
- await client.getCMSPagesByContentType('plp')
258
- now.mockReturnValue(11 * CACHE_BUST_WINDOW_MS)
259
- await client.getCMSPagesByContentType('plp')
260
-
261
- expect(paramsOfCall(1)?.get(CACHE_BUST_PARAM)).toBe('10')
262
- expect(paramsOfCall(3)?.get(CACHE_BUST_PARAM)).toBe('10')
263
- expect(paramsOfCall(5)?.get(CACHE_BUST_PARAM)).toBe('11')
264
- })
265
-
266
- describe('retry cooldown', () => {
267
- it('fails fast for a URL whose retry also failed', async () => {
268
- const client = createClient()
269
- baseFetch.mockRejectedValue(invalidJSON())
270
-
271
- await expect(
272
- client.getCMSPagesByContentType('plp')
273
- ).rejects.toBeInstanceOf(SyntaxError)
274
- expect(baseFetch).toHaveBeenCalledTimes(2)
275
-
276
- await expect(
277
- client.getCMSPagesByContentType('plp')
278
- ).rejects.toBeInstanceOf(SyntaxError)
279
- expect(baseFetch).toHaveBeenCalledTimes(3)
280
- // One warning for the retry and one for the cooldown.
281
- expect(warn).toHaveBeenCalledTimes(2)
282
- expect(warn.mock.calls[1][0]).toContain(
283
- 'Skipping retries for this URL for 60s'
284
- )
285
- })
286
-
287
- it('also backs off when the retry fails with another error', async () => {
288
- const client = createClient()
289
- const originError = new Error('Error while fetching')
290
- baseFetch
291
- .mockRejectedValueOnce(invalidJSON())
292
- .mockRejectedValueOnce(originError)
293
- .mockRejectedValueOnce(invalidJSON())
294
-
295
- await expect(client.getCMSPagesByContentType('plp')).rejects.toBe(
296
- originError
297
- )
298
- await expect(
299
- client.getCMSPagesByContentType('plp')
300
- ).rejects.toBeInstanceOf(SyntaxError)
301
- expect(baseFetch).toHaveBeenCalledTimes(3)
302
- })
303
-
304
- it('still retries other URLs', async () => {
305
- const client = createClient()
306
- const page = listingPage(2, 10, 20)
307
- baseFetch
308
- .mockRejectedValueOnce(invalidJSON())
309
- .mockRejectedValueOnce(invalidJSON())
310
- .mockRejectedValueOnce(invalidJSON())
311
- .mockResolvedValueOnce(page)
312
-
313
- await expect(
314
- client.getCMSPagesByContentType('plp')
315
- ).rejects.toBeInstanceOf(SyntaxError)
316
- await expect(
317
- client.getCMSPagesByContentType('plp', { page: 2 })
318
- ).resolves.toEqual(page)
319
- expect(baseFetch).toHaveBeenCalledTimes(4)
320
- })
321
-
322
- it('retries the URL again after the cooldown', async () => {
323
- const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000)
324
- const client = createClient()
325
- const page = listingPage(1, 1, 1)
326
- baseFetch
327
- .mockRejectedValueOnce(invalidJSON())
328
- .mockRejectedValueOnce(invalidJSON())
329
- .mockRejectedValueOnce(invalidJSON())
330
- .mockResolvedValueOnce(page)
331
-
332
- await expect(
333
- client.getCMSPagesByContentType('plp')
334
- ).rejects.toBeInstanceOf(SyntaxError)
335
-
336
- now.mockReturnValue(1_000_000 + RETRY_COOLDOWN_MS)
337
-
338
- await expect(client.getCMSPagesByContentType('plp')).resolves.toEqual(
339
- page
340
- )
341
- expect(baseFetch).toHaveBeenCalledTimes(4)
342
- // The retry after the cooldown uses a new cache-busting value.
343
- expect(paramsOfCall(3)?.get(CACHE_BUST_PARAM)).not.toBe(
344
- paramsOfCall(1)?.get(CACHE_BUST_PARAM)
345
- )
346
- })
347
-
348
- it('lasts at least one cache-busting window', () => {
349
- expect(RETRY_COOLDOWN_MS).toBeGreaterThanOrEqual(CACHE_BUST_WINDOW_MS)
350
- })
351
- })
352
-
353
- describe('with real HTTP responses', () => {
354
- // Real `fetch` and `response.json()` against a local server, like
355
- // `@vtex/client-cms` does, to pin the error shapes the runtime produces.
356
- // The server answers the bad body until the cache-busting param is sent,
357
- // and closes each connection so `server.close()` does not wait on sockets.
358
- const good: ContentPage = { data: [], hasNextPage: false, totalItems: 0 }
359
- const goodJSON = JSON.stringify(good)
360
- const badResponses: Record<
361
- string,
362
- { headers: Record<string, string>; body: string | Buffer }
363
- > = {
364
- 'gzip-without-content-encoding': {
365
- headers: {},
366
- body: gzipSync(goodJSON),
367
- },
368
- 'content-encoding-gzip-on-plain-body': {
369
- headers: { 'content-encoding': 'gzip' },
370
- body: goodJSON,
371
- },
372
- 'content-encoding-br-on-plain-body': {
373
- headers: { 'content-encoding': 'br' },
374
- body: goodJSON,
375
- },
376
- 'html-page': {
377
- headers: { 'content-type': 'text/html' },
378
- body: '<html>Error</html>',
379
- },
380
- 'truncated-json': { headers: {}, body: goodJSON.slice(0, 10) },
381
- }
382
-
383
- let server: Server
384
- let origin = ''
385
-
386
- beforeAll(async () => {
387
- server = createServer((req, res) => {
388
- const url = new URL(req.url ?? '/', 'http://localhost')
389
- const bad = badResponses[url.pathname.slice(1)]
390
-
391
- if (bad && !url.searchParams.has(CACHE_BUST_PARAM)) {
392
- res.writeHead(200, { ...bad.headers, connection: 'close' })
393
- res.end(bad.body)
394
- return
395
- }
396
-
397
- res.writeHead(200, {
398
- 'content-type': 'application/json',
399
- connection: 'close',
400
- })
401
- res.end(goodJSON)
402
- })
403
- await new Promise<void>((resolve) =>
404
- server.listen(0, '127.0.0.1', resolve)
405
- )
406
- origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
407
- })
408
-
409
- afterAll(async () => {
410
- await new Promise<void>((resolve) => server.close(() => resolve()))
411
- })
412
-
413
- beforeEach(() => {
414
- baseFetch.mockImplementation(
415
- async (path?: string, params?: URLSearchParams) => {
416
- const query = params?.toString()
417
- const response = await fetch(
418
- [`${origin}/${path}`, query].filter(Boolean).join('?')
419
- )
420
-
421
- if (!response.ok) {
422
- throw new Error('Error while fetching')
423
- }
424
-
425
- return response.json()
426
- }
427
- )
428
- })
429
-
430
- it.each(Object.keys(badResponses))(
431
- 'retries a %s response',
432
- async (name) => {
433
- await expect(
434
- createClient().getCMSPagesByContentType(name)
435
- ).resolves.toEqual(good)
436
- expect(baseFetch).toHaveBeenCalledTimes(2)
437
- }
438
- )
439
- })
440
-
441
- describe('getCMSPage', () => {
442
- // Page 1 says there are 25 items, so pages 2 and 3 are fetched in
443
- // parallel. Page 2 answers with an invalid body the first time.
444
- const mockListingWithOneBadPage = () => {
445
- let badResponses = 1
446
-
447
- baseFetch.mockImplementation(async (_path, params) => {
448
- const page = Number((params as URLSearchParams).get('page'))
449
-
450
- if (page === 2 && badResponses > 0) {
451
- badResponses -= 1
452
- throw invalidJSON()
453
- }
454
-
455
- return listingPage(page, page === 3 ? 5 : 10, 25)
456
- })
457
- }
458
-
459
- it('recovers when one page of a listing has an invalid body', async () => {
460
- mockListingWithOneBadPage()
461
-
462
- const result = await getCMSPage({ contentType: 'plp' }, createClient())
463
-
464
- expect(result.data).toHaveLength(25)
465
- expect(result.data[10].id).toBe('page-2-item-0')
466
- // Pages 1, 2 and 3, plus the retry of page 2.
467
- expect(baseFetch).toHaveBeenCalledTimes(4)
468
- expect(warn).toHaveBeenCalledTimes(1)
469
- expect(warn.mock.calls[0][0]).toContain('page=2')
470
- })
471
-
472
- it('is used by the default CMS client', async () => {
473
- mockListingWithOneBadPage()
474
-
475
- const result = await getCMSPage({ contentType: 'plp' }, clientCMS)
476
-
477
- expect(clientCMS).toBeInstanceOf(ResilientClientCMS)
478
- expect(result.data).toHaveLength(25)
479
- expect(baseFetch).toHaveBeenCalledTimes(4)
480
- })
481
- })
482
- })
@@ -1,118 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
-
3
- import type { toRevalidate as ToRevalidate } from 'src/utils/toRevalidate'
4
-
5
- const KEY = 'experimental.revalidatePLP'
6
-
7
- // The helper warns once per key per process, so each test loads a fresh
8
- // module to start with no warnings recorded.
9
- let toRevalidate: typeof ToRevalidate
10
-
11
- beforeEach(async () => {
12
- vi.resetModules()
13
- ;({ toRevalidate } = await import('src/utils/toRevalidate'))
14
- })
15
-
16
- afterEach(() => {
17
- vi.restoreAllMocks()
18
- })
19
-
20
- describe('toRevalidate', () => {
21
- it('returns the number of seconds when it is a positive integer', () => {
22
- expect(toRevalidate(300, KEY)).toBe(300)
23
- expect(toRevalidate(1, KEY)).toBe(1)
24
- })
25
-
26
- it('returns false without a warning when the window is disabled or unset', () => {
27
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
28
-
29
- expect(toRevalidate(false, KEY)).toBe(false)
30
- expect(toRevalidate(undefined, KEY)).toBe(false)
31
- expect(toRevalidate(null, KEY)).toBe(false)
32
- expect(warn).not.toHaveBeenCalled()
33
- })
34
-
35
- it.each([
36
- // Next.js throws for these.
37
- 0,
38
- -60,
39
- 90.5,
40
- 0.5,
41
- Number.NaN,
42
- Number.POSITIVE_INFINITY,
43
- '300',
44
- // Next.js reads `true` as 1 second; the config expects explicit seconds.
45
- true,
46
- ])('returns false and warns for %s', (value) => {
47
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
48
-
49
- expect(toRevalidate(value, KEY)).toBe(false)
50
- expect(warn).toHaveBeenCalledWith(expect.stringContaining(KEY))
51
- })
52
-
53
- it('prints the received value in the warning', () => {
54
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
55
-
56
- toRevalidate('300', 'a')
57
- toRevalidate(Number.NaN, 'b')
58
- toRevalidate({ seconds: 300 }, 'c')
59
-
60
- expect(warn).toHaveBeenNthCalledWith(1, expect.stringContaining('"300"'))
61
- expect(warn).toHaveBeenNthCalledWith(2, expect.stringContaining(': NaN.'))
62
- expect(warn).toHaveBeenNthCalledWith(
63
- 3,
64
- expect.stringContaining('a value of type object')
65
- )
66
- })
67
-
68
- it('does not throw for values JSON.stringify rejects', () => {
69
- vi.spyOn(console, 'warn').mockImplementation(() => {})
70
-
71
- const circular: Record<string, unknown> = {}
72
- circular.self = circular
73
-
74
- expect(toRevalidate(circular, 'a')).toBe(false)
75
- expect(toRevalidate({ seconds: BigInt(300) }, 'b')).toBe(false)
76
- expect(toRevalidate(BigInt(300), 'c')).toBe(false)
77
- })
78
-
79
- it('warns about an invalid value once per key', () => {
80
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
81
-
82
- toRevalidate('300', KEY)
83
- toRevalidate('300', KEY)
84
-
85
- expect(warn).toHaveBeenCalledTimes(1)
86
- })
87
-
88
- describe('with a minimum', () => {
89
- it('raises a lower window to the minimum and warns once', () => {
90
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
91
-
92
- expect(toRevalidate(30, KEY, { min: 60 })).toBe(60)
93
- expect(toRevalidate(30, KEY, { min: 60 })).toBe(60)
94
- expect(toRevalidate(1, KEY, { min: 60 })).toBe(60)
95
- expect(warn).toHaveBeenCalledTimes(1)
96
- expect(warn).toHaveBeenCalledWith(
97
- `[FastStore] ${KEY} is 30s. Using the minimum of 60s.`
98
- )
99
- })
100
-
101
- it('keeps windows at or above the minimum', () => {
102
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
103
-
104
- expect(toRevalidate(60, KEY, { min: 60 })).toBe(60)
105
- expect(toRevalidate(120, KEY, { min: 60 })).toBe(120)
106
- expect(warn).not.toHaveBeenCalled()
107
- })
108
-
109
- it('still returns false for invalid values', () => {
110
- vi.spyOn(console, 'warn').mockImplementation(() => {})
111
-
112
- expect(toRevalidate(0, KEY, { min: 60 })).toBe(false)
113
- expect(toRevalidate(30.5, 'a', { min: 60 })).toBe(false)
114
- expect(toRevalidate('30', 'b', { min: 60 })).toBe(false)
115
- expect(toRevalidate(false, 'c', { min: 60 })).toBe(false)
116
- })
117
- })
118
- })