/
composables.test.ts
644 lines (580 loc) · 20.4 KB
/
composables.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/// <reference path="../fixtures/basic/.nuxt/nuxt.d.ts" />
import { describe, expect, it, vi } from 'vitest'
import { defineEventHandler } from 'h3'
import { mount } from '@vue/test-utils'
import { mountSuspended, registerEndpoint } from '@nuxt/test-utils/runtime'
import * as composables from '#app/composables'
import { clearNuxtData, refreshNuxtData, useAsyncData, useNuxtData } from '#app/composables/asyncData'
import { clearError, createError, isNuxtError, showError, useError } from '#app/composables/error'
import { onNuxtReady } from '#app/composables/ready'
import { setResponseStatus, useRequestEvent, useRequestFetch, useRequestHeaders } from '#app/composables/ssr'
import { clearNuxtState, useState } from '#app/composables/state'
import { useRequestURL } from '#app/composables/url'
import { getAppManifest, getRouteRules } from '#app/composables/manifest'
import { useId } from '#app/composables/id'
import { callOnce } from '#app/composables/once'
import { useLoadingIndicator } from '#app/composables/loading-indicator'
vi.mock('#app/compat/idle-callback', () => ({
requestIdleCallback: (cb: Function) => cb()
}))
const timestamp = Date.now()
registerEndpoint('/_nuxt/builds/latest.json', defineEventHandler(() => ({
id: 'override',
timestamp
})))
registerEndpoint('/_nuxt/builds/meta/override.json', defineEventHandler(() => ({
id: 'override',
timestamp,
matcher: {
static: {
'/': null,
'/pre': null,
'/pre/test': { redirect: true }
},
wildcard: { '/pre': { prerender: true } },
dynamic: {}
},
prerendered: ['/specific-prerendered']
})))
registerEndpoint('/api/test', defineEventHandler((event) => ({
method: event.method,
headers: Object.fromEntries(event.headers.entries())
})))
describe('app config', () => {
it('can be updated', () => {
const appConfig = useAppConfig()
expect(appConfig).toMatchInlineSnapshot(`
{
"nuxt": {
"buildId": "override",
},
}
`)
updateAppConfig({
new: 'value',
// @ts-expect-error property does not exist
nuxt: { nested: 42 }
})
expect(appConfig).toMatchInlineSnapshot(`
{
"new": "value",
"nuxt": {
"buildId": "override",
"nested": 42,
},
}
`)
})
})
describe('composables', () => {
it('are all tested', () => {
const testedComposables: string[] = [
'clearNuxtData',
'refreshNuxtData',
'useAsyncData',
'useNuxtData',
'createError',
'isNuxtError',
'clearError',
'showError',
'useError',
'getAppManifest',
'useHydration',
'getRouteRules',
'onNuxtReady',
'callOnce',
'setResponseStatus',
'prerenderRoutes',
'useRequestEvent',
'useRequestFetch',
'isPrerendered',
'useRequestHeaders',
'clearNuxtState',
'useState',
'useRequestURL',
'useId',
'useRoute',
'navigateTo',
'abortNavigation',
'setPageLayout',
'defineNuxtComponent',
]
const skippedComposables: string[] = [
'addRouteMiddleware',
'defineNuxtRouteMiddleware',
'definePayloadReducer',
'definePayloadReviver',
'loadPayload',
'onBeforeRouteLeave',
'onBeforeRouteUpdate',
'prefetchComponents',
'preloadComponents',
'preloadPayload',
'preloadRouteComponents',
'reloadNuxtApp',
'refreshCookie',
'useCookie',
'useFetch',
'useHead',
'useLazyFetch',
'useLazyAsyncData',
'useRouter',
'useSeoMeta',
'useServerSeoMeta'
]
expect(Object.keys(composables).sort()).toEqual([...new Set([...testedComposables, ...skippedComposables])].sort())
})
})
describe('useAsyncData', () => {
it('should work at basic level', async () => {
const res = useAsyncData(() => Promise.resolve('test'))
expect(Object.keys(res)).toMatchInlineSnapshot(`
[
"data",
"pending",
"error",
"status",
"execute",
"refresh",
]
`)
expect(res instanceof Promise).toBeTruthy()
expect(res.data.value).toBe(null)
await res
expect(res.data.value).toBe('test')
})
it('should not execute with immediate: false', async () => {
const immediate = await useAsyncData(() => Promise.resolve('test'))
expect(immediate.data.value).toBe('test')
expect(immediate.status.value).toBe('success')
expect(immediate.pending.value).toBe(false)
const nonimmediate = await useAsyncData(() => Promise.resolve('test'), { immediate: false })
expect(nonimmediate.data.value).toBe(null)
expect(nonimmediate.status.value).toBe('idle')
expect(nonimmediate.pending.value).toBe(true)
})
it('should capture errors', async () => {
const { data, error, status, pending } = await useAsyncData('error-test', () => Promise.reject(new Error('test')), { default: () => 'default' })
expect(data.value).toMatchInlineSnapshot('"default"')
expect(error.value).toMatchInlineSnapshot('[Error: test]')
expect(status.value).toBe('error')
expect(pending.value).toBe(false)
expect(useNuxtApp().payload._errors['error-test']).toMatchInlineSnapshot('[Error: test]')
// TODO: fix the below
// const { data: syncedData, error: syncedError, status: syncedStatus, pending: syncedPending } = await useAsyncData('error-test', () => ({}), { immediate: false })
// expect(syncedData.value).toEqual(null)
// expect(syncedError.value).toEqual(error.value)
// expect(syncedStatus.value).toEqual('idle')
// expect(syncedPending.value).toEqual(true)
})
// https://github.com/nuxt/nuxt/issues/23411
it('should initialize with error set to null when immediate: false', async () => {
const { error, execute } = useAsyncData(() => ({}), { immediate: false })
expect(error.value).toBe(null)
await execute()
expect(error.value).toBe(null)
})
it('should be accessible with useNuxtData', async () => {
await useAsyncData('key', () => Promise.resolve('test'))
const data = useNuxtData('key')
expect(data.data.value).toMatchInlineSnapshot('"test"')
clearNuxtData('key')
expect(data.data.value).toBeUndefined()
expect(useNuxtData('key').data.value).toBeUndefined()
})
it('should be usable _after_ a useNuxtData call', async () => {
useNuxtApp().payload.data.call = null
const { data: cachedData } = useNuxtData('call')
expect(cachedData.value).toMatchInlineSnapshot('null')
const { data } = await useAsyncData('call', () => Promise.resolve({ resolved: true }), { server: false })
expect(cachedData.value).toMatchInlineSnapshot(`
{
"resolved": true,
}
`)
expect(data.value).toEqual(cachedData.value)
clearNuxtData('call')
})
it('should be refreshable', async () => {
await useAsyncData('key', () => Promise.resolve('test'))
clearNuxtData('key')
const data = useNuxtData('key')
expect(data.data.value).toBeUndefined()
await refreshNuxtData('key')
expect(data.data.value).toMatchInlineSnapshot('"test"')
})
it('allows custom access to a cache', async () => {
const { data } = await useAsyncData(() => ({ val: true }), { getCachedData: () => ({ val: false }) })
expect(data.value).toMatchInlineSnapshot(`
{
"val": false,
}
`)
})
it('should use default while pending', async () => {
const promise = useAsyncData(() => Promise.resolve('test'), { default: () => 'default' })
const { data, pending } = promise
expect(pending.value).toBe(true)
expect(data.value).toMatchInlineSnapshot('"default"')
await promise
expect(data.value).toMatchInlineSnapshot('"test"')
})
it('should use default after reject', async () => {
const { data } = await useAsyncData(() => Promise.reject(new Error('test')), { default: () => 'default' })
expect(data.value).toMatchInlineSnapshot('"default"')
})
it('should execute the promise function once when dedupe option is "defer" for multiple calls', async () => {
const promiseFn = vi.fn(() => Promise.resolve('test'))
useAsyncData('dedupedKey', promiseFn, { dedupe: 'defer' })
useAsyncData('dedupedKey', promiseFn, { dedupe: 'defer' })
useAsyncData('dedupedKey', promiseFn, { dedupe: 'defer' })
expect(promiseFn).toHaveBeenCalledTimes(1)
})
it('should execute the promise function multiple times when dedupe option is not specified for multiple calls', async () => {
const promiseFn = vi.fn(() => Promise.resolve('test'))
useAsyncData('dedupedKey', promiseFn)
useAsyncData('dedupedKey', promiseFn)
useAsyncData('dedupedKey', promiseFn)
expect(promiseFn).toHaveBeenCalledTimes(3)
})
it('should execute the promise function as per dedupe option when different dedupe options are used for multiple calls', async () => {
const promiseFn = vi.fn(() => Promise.resolve('test'))
useAsyncData('dedupedKey', promiseFn, { dedupe: 'defer' })
useAsyncData('dedupedKey', promiseFn)
useAsyncData('dedupedKey', promiseFn, { dedupe: 'defer' })
expect(promiseFn).toHaveBeenCalledTimes(2)
})
})
describe('useFetch', () => {
it('should match with/without computed values', async () => {
const nuxtApp = useNuxtApp()
const getPayloadEntries = () => Object.keys(nuxtApp.payload.data).length
const baseCount = getPayloadEntries()
await useFetch('/api/test')
expect(getPayloadEntries()).toBe(baseCount + 1)
/* @ts-expect-error Overriding auto-key */
await useFetch('/api/test', { method: 'POST' }, '')
/* @ts-expect-error Overriding auto-key */
await useFetch('/api/test', { method: ref('POST') }, '')
expect.soft(getPayloadEntries()).toBe(baseCount + 2)
/* @ts-expect-error Overriding auto-key */
await useFetch('/api/test', { query: { id: '3' } }, '')
/* @ts-expect-error Overriding auto-key */
await useFetch('/api/test', { query: { id: ref('3') } }, '')
/* @ts-expect-error Overriding auto-key */
await useFetch('/api/test', { params: { id: '3' } }, '')
/* @ts-expect-error Overriding auto-key */
await useFetch('/api/test', { params: { id: ref('3') } }, '')
expect.soft(getPayloadEntries()).toBe(baseCount + 3)
})
it('should timeout', async () => {
const { status, error } = await useFetch(
() => new Promise(resolve => setTimeout(resolve, 5000)),
{ timeout: 1 }
)
await new Promise(resolve => setTimeout(resolve, 2))
expect(status.value).toBe('error')
expect(error.value).toMatchInlineSnapshot('[Error: [GET] "[object Promise]": <no response> The operation was aborted.]')
})
})
describe('errors', () => {
it('createError', () => {
expect(createError({ statusCode: 404 }).toJSON()).toMatchInlineSnapshot(`
{
"message": "",
"statusCode": 404,
}
`)
expect(createError('Message').toJSON()).toMatchInlineSnapshot(`
{
"message": "Message",
"statusCode": 500,
}
`)
})
it('isNuxtError', () => {
const error = createError({ statusCode: 404 })
expect(isNuxtError(error)).toBe(true)
expect(isNuxtError(new Error('test'))).toBe(false)
})
it('global nuxt errors', () => {
const err = useError()
expect(err.value).toBeUndefined()
showError('new error')
expect(err.value).toMatchInlineSnapshot('[Error: new error]')
clearError()
// TODO: should this return to being undefined?
expect(err.value).toBeNull()
})
})
describe('onNuxtReady', () => {
it('should call callback once nuxt is hydrated', async () => {
const fn = vi.fn()
onNuxtReady(fn)
await new Promise(resolve => setTimeout(resolve, 1))
expect(fn).toHaveBeenCalled()
})
})
describe('ssr composables', () => {
it('work on client', () => {
// @ts-expect-error This should work for backward compatibility
expect(setResponseStatus()).toBeUndefined()
expect(useRequestEvent()).toBeUndefined()
expect(useRequestFetch()).toEqual($fetch)
expect(useRequestHeaders()).toEqual({})
expect(prerenderRoutes('/')).toBeUndefined()
})
})
describe('useHydration', () => {
it('should hydrate value from payload', async () => {
let val: any
const nuxtApp = useNuxtApp()
useHydration('key', () => {}, (fromPayload) => { val = fromPayload })
await nuxtApp.hooks.callHook('app:created', nuxtApp.vueApp)
expect(val).toMatchInlineSnapshot('undefined')
nuxtApp.payload.key = 'from payload'
await nuxtApp.hooks.callHook('app:created', nuxtApp.vueApp)
expect(val).toMatchInlineSnapshot('"from payload"')
})
})
describe('useState', () => {
it('default', () => {
expect(useState(() => 'default').value).toBe('default')
})
it('registers state in payload', () => {
useState('key', () => 'value')
expect(Object.entries(useNuxtApp().payload.state)).toContainEqual(['$skey', 'value'])
})
})
describe('clearNuxtState', () => {
it('clears state in payload for single key', () => {
const key = 'clearNuxtState-test'
const state = useState(key, () => 'test')
expect(state.value).toBe('test')
clearNuxtState(key)
expect(state.value).toBeUndefined()
})
it('clears state in payload for array of keys', () => {
const key1 = 'clearNuxtState-test'
const key2 = 'clearNuxtState-test2'
const state1 = useState(key1, () => 'test')
const state2 = useState(key2, () => 'test')
expect(state1.value).toBe('test')
expect(state2.value).toBe('test')
clearNuxtState([key1, 'other'])
expect(state1.value).toBeUndefined()
expect(state2.value).toBe('test')
clearNuxtState([key1, key2])
expect(state1.value).toBeUndefined()
expect(state2.value).toBeUndefined()
})
it('clears state in payload for function', () => {
const key = 'clearNuxtState-test'
const state = useState(key, () => 'test')
expect(state.value).toBe('test')
clearNuxtState(() => false)
expect(state.value).toBe('test')
clearNuxtState(k => k === key)
expect(state.value).toBeUndefined()
})
it('clears all state when no key is provided', () => {
const state1 = useState('clearNuxtState-test', () => 'test')
const state2 = useState('clearNuxtState-test2', () => 'test')
expect(state1.value).toBe('test')
expect(state2.value).toBe('test')
clearNuxtState()
expect(state1.value).toBeUndefined()
expect(state2.value).toBeUndefined()
})
})
describe('useId', () => {
it('default', () => {
const vals = new Set<string>()
for (let index = 0; index < 100; index++) {
mount(defineComponent({
setup () {
const id = useId()
vals.add(id)
return () => h('div', id)
}
}))
}
expect(vals.size).toBe(100)
})
it('generates unique ids per-component', () => {
const component = defineComponent({
setup () {
const id = useId()
return () => h('div', id)
}
})
expect(mount(component).html()).not.toBe(mount(component).html())
})
})
describe('url', () => {
it('useRequestURL', () => {
const url = useRequestURL()
expect(url).toMatchInlineSnapshot('"http://localhost:3000/"')
expect(url.hostname).toMatchInlineSnapshot('"localhost"')
expect(url.port).toMatchInlineSnapshot('"3000"')
expect(url.protocol).toMatchInlineSnapshot('"http:"')
})
})
describe('loading state', () => {
it('expect loading state to be changed by hooks', async () => {
vi.stubGlobal('setTimeout', vi.fn((cb: Function) => cb()))
const nuxtApp = useNuxtApp()
const { isLoading } = useLoadingIndicator()
expect(isLoading.value).toBeFalsy()
await nuxtApp.callHook('page:loading:start')
expect(isLoading.value).toBeTruthy()
await nuxtApp.callHook('page:loading:end')
expect(isLoading.value).toBeFalsy()
vi.mocked(setTimeout).mockRestore()
})
})
describe.skipIf(process.env.TEST_MANIFEST === 'manifest-off')('app manifests', () => {
it('getAppManifest', async () => {
const manifest = await getAppManifest()
delete manifest.timestamp
expect(manifest).toMatchInlineSnapshot(`
{
"id": "override",
"matcher": {
"dynamic": {},
"static": {
"/": null,
"/pre": null,
"/pre/test": {
"redirect": true,
},
},
"wildcard": {
"/pre": {
"prerender": true,
},
},
},
"prerendered": [
"/specific-prerendered",
],
}
`)
})
it('getRouteRules', async () => {
expect(await getRouteRules('/')).toMatchInlineSnapshot('{}')
expect(await getRouteRules('/pre')).toMatchInlineSnapshot(`
{
"prerender": true,
}
`)
expect(await getRouteRules('/pre/test')).toMatchInlineSnapshot(`
{
"prerender": true,
"redirect": true,
}
`)
})
it('isPrerendered', async () => {
expect(await isPrerendered('/specific-prerendered')).toBeTruthy()
expect(await isPrerendered('/prerendered/test')).toBeTruthy()
expect(await isPrerendered('/test')).toBeFalsy()
expect(await isPrerendered('/pre/test')).toBeFalsy()
expect(await isPrerendered('/pre/thing')).toBeTruthy()
})
})
describe('routing utilities: `navigateTo`', () => {
it('navigateTo should disallow navigation to external URLs by default', () => {
expect(() => navigateTo('https://test.com')).toThrowErrorMatchingInlineSnapshot(`[Error: Navigating to an external URL is not allowed by default. Use \`navigateTo(url, { external: true })\`.]`)
expect(() => navigateTo('https://test.com', { external: true })).not.toThrow()
})
it('navigateTo should disallow navigation to data/script URLs', () => {
const urls = [
['data:alert("hi")', 'data'],
['\0data:alert("hi")', 'data'],
]
for (const [url, protocol] of urls) {
expect(() => navigateTo(url, { external: true })).toThrowError(`Cannot navigate to a URL with '${protocol}:' protocol.`)
}
})
})
describe('routing utilities: `useRoute`', () => {
it('should show provide a mock route', async () => {
expect(useRoute()).toMatchObject({
fullPath: '/',
hash: '',
href: '/',
matched: [],
meta: {},
name: undefined,
params: {},
path: '/',
query: {},
redirectedFrom: undefined,
})
})
})
describe('routing utilities: `abortNavigation`', () => {
it('should throw an error if one is provided', () => {
const error = useError()
expect(() => abortNavigation({ message: 'Page not found' })).toThrowErrorMatchingInlineSnapshot(`[Error: Page not found]`)
expect(error.value).toBeFalsy()
})
it('should block navigation if no error is provided', () => {
expect(abortNavigation()).toMatchInlineSnapshot('false')
})
})
describe('routing utilities: `setPageLayout`', () => {
it('should set error on page metadata if run outside middleware', () => {
const route = useRoute()
expect(route.meta.layout).toBeUndefined()
setPageLayout('custom')
expect(route.meta.layout).toEqual('custom')
route.meta.layout = undefined
})
it('should not set layout directly if run within middleware', async () => {
const route = useRoute()
const nuxtApp = useNuxtApp()
nuxtApp._processingMiddleware = true
setPageLayout('custom')
expect(route.meta.layout).toBeUndefined()
nuxtApp._processingMiddleware = false
})
})
describe('defineNuxtComponent', () => {
it('should produce a Vue component', async () => {
const wrapper = await mountSuspended(defineNuxtComponent({
render: () => h('div', 'hi there')
}))
expect(wrapper.html()).toMatchInlineSnapshot('"<div>hi there</div>"')
})
it.todo('should support Options API asyncData')
it.todo('should support Options API head')
})
describe('callOnce', () => {
it('should only call composable once', async () => {
const fn = vi.fn()
const execute = () => callOnce(fn)
await execute()
await execute()
expect(fn).toHaveBeenCalledTimes(1)
})
it('should only call composable once when called in parallel', async () => {
const fn = vi.fn().mockImplementation(() => new Promise(resolve => setTimeout(resolve, 1)))
const execute = () => callOnce(fn)
await Promise.all([execute(), execute(), execute()])
expect(fn).toHaveBeenCalledTimes(1)
const fnSync = vi.fn().mockImplementation(() => { })
const executeSync = () => callOnce(fnSync)
await Promise.all([executeSync(), executeSync(), executeSync()])
expect(fnSync).toHaveBeenCalledTimes(1)
})
it('should use key to dedupe', async () => {
const fn = vi.fn()
const execute = (key?: string) => callOnce(key, fn)
await execute('first')
await execute('first')
await execute('second')
expect(fn).toHaveBeenCalledTimes(2)
})
})