Skip to content

Commit e03e1c0

Browse files
authored
fix(runtime): allow registerEndpoint to work with $fetch.create (#1403)
1 parent 749b484 commit e03e1c0

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<script setup lang="ts">
2+
async function normalFetcher() {
3+
const fetcher = $fetch.create({})
4+
await fetcher('/test1/')
5+
}
6+
7+
async function customFetcher() {
8+
const fetcher = $fetch.create({
9+
onRequest() {},
10+
})
11+
await fetcher('/test2/')
12+
}
13+
</script>
14+
15+
<template>
16+
<div>
17+
<button
18+
id="normal-fetcher"
19+
@click="normalFetcher"
20+
>
21+
normal fetch
22+
</button>
23+
<button
24+
id="custom-fetcher"
25+
@click="customFetcher"
26+
>
27+
custom fetch
28+
</button>
29+
</div>
30+
</template>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { mountSuspended, registerEndpoint } from '@nuxt/test-utils/runtime'
2+
import { it, expect, vi, describe } from 'vitest'
3+
import TestFetchComponent from '../components/TestFetchComponent.vue'
4+
5+
describe('registerEndpoint tests', () => {
6+
it('/test1/ called WITHOUT onRequest intercepted', async () => {
7+
const endpoint = vi.fn(() => '')
8+
registerEndpoint('/test1/', () => endpoint())
9+
const component = await mountSuspended(TestFetchComponent)
10+
11+
component
12+
.find<HTMLButtonElement>('#normal-fetcher')
13+
.element.click()
14+
15+
expect(endpoint).toHaveBeenCalled()
16+
component.unmount()
17+
})
18+
19+
it('/test2/ called WITH onRequest intercepted', async () => {
20+
const endpoint = vi.fn(() => '')
21+
registerEndpoint('/test2/', () => endpoint())
22+
const component = await mountSuspended(TestFetchComponent)
23+
24+
component
25+
.find<HTMLButtonElement>('#custom-fetcher')
26+
.element.click()
27+
28+
expect(endpoint).toHaveBeenCalled()
29+
component.unmount()
30+
})
31+
})

src/runtime/shared/environment.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ export async function setupWindow(win: NuxtWindow, environmentOptions: { nuxt: N
7474
// @ts-expect-error fetch types differ slightly
7575
win.$fetch = createFetch({ fetch: win.fetch, Headers: win.Headers })
7676

77+
// @ts-expect-error fetch types differ slightly
78+
win.$fetch.create = (options = {}) => {
79+
return createFetch({ fetch: win.fetch, Headers: win.Headers, ...options })
80+
}
81+
7782
win.__registry = registry
7883
win.__app = h3App
7984

0 commit comments

Comments
 (0)