|
1 | | -import { describe, expect, it } from 'vitest' |
| 1 | +import { describe, expect, it, vi } from 'vitest' |
2 | 2 |
|
3 | 3 | import { mountSuspended, registerEndpoint } from '@nuxt/test-utils/runtime' |
4 | 4 |
|
@@ -176,4 +176,53 @@ describe('server mocks and data fetching', () => { |
176 | 176 | expect(await fetch(new URL('http://localhost:3000/with-url')).then(res => res.json())).toMatchObject({ title: 'with-url', data: {} }) |
177 | 177 | expect(await fetch(new URL('http://localhost:3000/with-url?q=1')).then(res => res.json())).toMatchObject({ title: 'with-url', data: { q: '1' } }) |
178 | 178 | }) |
| 179 | + |
| 180 | + it('can mock fetch requests with fetch.create', async () => { |
| 181 | + registerEndpoint('/fetch-create/1', event => ({ |
| 182 | + title: 'title from mocked api1', |
| 183 | + headers: getHeaders(event), |
| 184 | + })) |
| 185 | + registerEndpoint('/fetch-create/2', event => ({ |
| 186 | + title: 'title from mocked api2', |
| 187 | + headers: getHeaders(event), |
| 188 | + })) |
| 189 | + registerEndpoint('/fetch-create/error', () => |
| 190 | + new Response(undefined, { status: 500, statusText: 'Mock Server Error' }), |
| 191 | + ) |
| 192 | + |
| 193 | + const onRequest = vi.fn() |
| 194 | + const onResponse = vi.fn() |
| 195 | + const onRequestError = vi.fn() |
| 196 | + const onResponseError = vi.fn() |
| 197 | + |
| 198 | + const fetch = $fetch.create({ |
| 199 | + baseURL: '/fetch-create', |
| 200 | + retry: false, |
| 201 | + onRequest, |
| 202 | + onResponse, |
| 203 | + onRequestError, |
| 204 | + onResponseError, |
| 205 | + headers: { |
| 206 | + authorization: 'Bearer <access_token>', |
| 207 | + }, |
| 208 | + }) |
| 209 | + |
| 210 | + expect(await fetch<unknown>('/1')).toMatchObject({ |
| 211 | + title: 'title from mocked api1', |
| 212 | + headers: { authorization: 'Bearer <access_token>' }, |
| 213 | + }) |
| 214 | + |
| 215 | + expect(await fetch<unknown>('/2')).toMatchObject({ |
| 216 | + title: 'title from mocked api2', |
| 217 | + headers: { authorization: 'Bearer <access_token>' }, |
| 218 | + }) |
| 219 | + |
| 220 | + await expect(fetch<unknown>('/error')).rejects.toMatchObject({ status: 500, statusText: 'Mock Server Error' }) |
| 221 | + await expect(fetch<unknown>('/error', { baseURL: '"INVALID"' })).rejects.toThrowError() |
| 222 | + |
| 223 | + expect(onRequest).toBeCalledTimes(4) |
| 224 | + expect(onResponse).toBeCalledTimes(3) |
| 225 | + expect(onRequestError).toBeCalledTimes(1) |
| 226 | + expect(onResponseError).toBeCalledTimes(1) |
| 227 | + }) |
179 | 228 | }) |
0 commit comments