Skip to content

Commit d547246

Browse files
feat!: rename $fetch export to $fetchRaw (closes #10)
1 parent 5052c45 commit d547246

File tree

4 files changed

+93
-19
lines changed

4 files changed

+93
-19
lines changed

README.md

Lines changed: 87 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ The main goal for this package is to provide a simple and easy-to-use testing en
99
- 🥜 Run Nitro per test suite or globally
1010
- ✅ Seamless integration with Vitest
1111
- 🪝 Conditional code execution based on test mode (`import.meta.test`)
12-
- 📡 Familiar [`$fetch`](#fetch) helper like Nuxt test utils
12+
- 📡 Familiar [`$fetchRaw`](#fetchRaw) helper similar to Nuxt test utils
1313

1414
## Installation
1515

@@ -56,12 +56,12 @@ Write your tests in a dedicated location, e.g. a `tests` directory. You can use
5656
A simple teste case could look like this:
5757

5858
```ts
59-
import { $fetch } from 'nitro-test-utils/e2e'
59+
import { $fetchRaw } from 'nitro-test-utils/e2e'
6060
import { describe, expect, it } from 'vitest'
6161

6262
describe('api', () => {
6363
it('responds successfully', async () => {
64-
const { data, status } = await $fetch('/api/health')
64+
const { data, status } = await $fetchRaw('/api/health')
6565

6666
expect(status).toBe(200)
6767
expect(data).toMatchSnapshot()
@@ -84,11 +84,11 @@ export default defineConfig()
8484

8585
Contrary to the global setup, the Nitro server is not started automatically by Vitest. Instead, you need to call the `setup` function in each test suite to start the Nitro server. After each test suite, the Nitro server is shut down.
8686

87-
Use the `nitro-test-utils/e2e` module to import the `setup` function and the `$fetch` helper. The `setup` function accepts an options object with the `rootDir` property, which should point to the directory where the Nitro server is located. For more options, see the [Configuration](#configuration) section.
87+
Use the `nitro-test-utils/e2e` module to import the `setup` function and the `$fetchRaw` helper. The `setup` function accepts an options object with the `rootDir` property, which should point to the directory where the Nitro server is located. For more options, see the [Configuration](#configuration) section.
8888

8989
```ts
9090
import { fileURLToPath } from 'node:url'
91-
import { $fetch, setup } from 'nitro-test-utils/e2e'
91+
import { $fetchRaw, setup } from 'nitro-test-utils/e2e'
9292
import { describe, expect, it } from 'vitest'
9393

9494
describe('api', async () => {
@@ -97,7 +97,7 @@ describe('api', async () => {
9797
})
9898

9999
it('responds successfully', async () => {
100-
const { data, status } = await $fetch('/api/health')
100+
const { data, status } = await $fetchRaw('/api/health')
101101

102102
expect(status).toBe(200)
103103
expect(data).toMatchSnapshot()
@@ -217,19 +217,69 @@ describe('api', async () => {
217217

218218
## Test Utilities
219219

220-
### `$fetch`
220+
### `injectServerUrl`
221221

222-
The `$fetch` function is a simple wrapper around [`ofetch`](https://github.com/unjs/ofetch) and is used to make requests to your Nitro server during testing. Import the function from the `nitro-test-utils/e2e` module. It will dynamically use the base URL of the active test server.
222+
To get the URL of the active test server for the current test suite or global test environment, you can use the `injectServerUrl` function.
223223

224-
`$fetch` returns a promise that resolves with the raw response from [`ofetch.raw`](https://github.com/unjs/ofetch?tab=readme-ov-file#-access-to-raw-response). This is useful because it allows you to access the response status code, headers, and body, even if the response failed.
224+
**Usage:**
225+
226+
```ts
227+
import { injectServerUrl } from 'nitro-test-utils/e2e'
228+
229+
describe('api', () => {
230+
it('should log the Nitro server URL', async () => {
231+
const serverUrl = injectServerUrl()
232+
console.log(serverUrl) // http://localhost:3000
233+
})
234+
})
235+
```
236+
237+
**Type Declaration:**
238+
239+
```ts
240+
function injectServerUrl(): string
241+
```
242+
243+
### `createFetch`
244+
245+
Creates a custom [`ofetch`](https://github.com/unjs/ofetch) instance with the Nitro server URL as the base URL.
246+
247+
> [!TIP]
248+
> The following additional fetch options have been set as defaults:
249+
>
250+
> - `ignoreResponseError: true` to prevent throwing errors on non-2xx responses.
251+
> - `redirect: 'manual'` to prevent automatic redirects.
252+
> - `headers: { accept: 'application/json' }` to force a JSON error response when Nitro returns an error.
253+
254+
**Usage:**
255+
256+
Inside a test case:
257+
258+
```ts
259+
import { createFetch } from 'nitro-test-utils/e2e'
260+
261+
const $fetch = createFetch()
262+
```
263+
264+
**Type Declaration:**
265+
266+
```ts
267+
function createFetch(): $Fetch
268+
```
269+
270+
### `$fetchRaw`
271+
272+
The `$fetchRaw` function is a simple wrapper around the custom [`ofetch`](https://github.com/unjs/ofetch) `$Fetch` instance created by `createFetch`. It simplifies requesting data from your Nitro server during testing. Import the function from the `nitro-test-utils/e2e` module. It will dynamically use the base URL of the active test server.
273+
274+
`$fetchRaw` returns a promise that resolves with the raw response from [`ofetch.raw`](https://github.com/unjs/ofetch?tab=readme-ov-file#-access-to-raw-response). This is useful because it allows you to access the response status code, headers, and body, even if the response failed.
225275

226276
**Usage:**
227277

228278
Inside a test case:
229279

230280
```ts
231281
// Use `data` instead of `body` for the parsed response body
232-
const { data, status, headers } = await $fetch('/api/hello')
282+
const { data, status, headers } = await $fetchRaw('/api/hello')
233283
234284
expect(status).toBe(200)
235285
expect(data).toMatchSnapshot()
@@ -238,17 +288,41 @@ expect(data).toMatchSnapshot()
238288
**Type Declaration:**
239289

240290
```ts
241-
function $fetch<T = any, R extends ResponseType = 'json'>(
291+
interface TestFetchResponse<T> extends FetchResponse<T> {
292+
/** Alias for `response._data` */
293+
data?: T
294+
}
295+
296+
function $fetchRaw<T = any, R extends ResponseType = 'json'>(
242297
path: string,
243298
options?: FetchOptions<R>
244-
): Promise<FetchResponse<MappedResponseType<R, T>>>
299+
): Promise<TestFetchResponse<MappedResponseType<R, T>>>
245300
```
246301

247302
> [!TIP]
248-
> Fetch options will be merged with sensible default options, like [`ignoreResponseError`](https://github.com/unjs/ofetch?tab=readme-ov-file#%EF%B8%8F-handling-errors) set to `true` to prevent the function from throwing an error when the response status code is not in the range of 200-299.
303+
> All additional options set in [`createFetch`](#createfetch) apply here as well, sucg has [`ignoreResponseError`](https://github.com/unjs/ofetch?tab=readme-ov-file#%EF%B8%8F-handling-errors) set to `true` to prevent the function from throwing an error when the response status code is not in the range of 200-299.
249304

250305
## Migration
251306

307+
### From v0.8 to v0.9
308+
309+
In v0.8 and earlier, `$fetch` returned an object, contrary to what `$fetch` does in Nitro, Nuxt (client and server) and ofetch itself, which returns the response body. Using the same name is a fragmentation that causes the same function to behave differently in test utilities.
310+
311+
As such, the `$fetch` function has been renamed to `$fetchRaw` to better reflect its behavior. To update your tests, simply rename the import and function call:
312+
313+
```diff
314+
-import { $fetch } from '../src/e2e'
315+
+import { $fetchRaw } from '../src/e2e'
316+
317+
describe('api', async () => {
318+
it('should respond data', async () => {
319+
- const { status } = await $fetch('/')
320+
+ const { status } = await $fetchRaw('/')
321+
expect(status).toBe(200)
322+
})
323+
})
324+
```
325+
252326
### From v0.7 to v0.8
253327

254328
The Nitro test utilities have been rewritten to provide flexible Nitro setups per test suite. The global Nitro setup was previously implicit and is now explicit. To upgrade and keep the same testing behavior, add the `global` option to the Nitro configuration in the `vitest.config.ts` file:

src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
export { $fetch, setup } from './e2e'
1+
export { $fetchRaw, createFetch, injectServerUrl, setup } from './e2e'
22

33
export * from './types'

test/production.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { fileURLToPath } from 'node:url'
22
import { describe, expect, it } from 'vitest'
3-
import { $fetch, setup } from '../src/e2e'
3+
import { $fetchRaw, setup } from '../src/e2e'
44

55
describe('production', async () => {
66
await setup({
@@ -9,7 +9,7 @@ describe('production', async () => {
99
})
1010

1111
it('should respond from production server build', async () => {
12-
const { data } = await $fetch('/')
12+
const { data } = await $fetchRaw('/')
1313
expect(data).toBe('Hello, production build!')
1414
})
1515
})

test/routes.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import { fileURLToPath } from 'node:url'
22
import { describe, expect, it } from 'vitest'
3-
import { $fetch, setup } from '../src/e2e'
3+
import { $fetchRaw, setup } from '../src/e2e'
44

55
describe('routes', async () => {
66
await setup({
77
rootDir: fileURLToPath(new URL('fixture', import.meta.url)),
88
})
99

1010
it('should respond with 200 status code', async () => {
11-
const { data } = await $fetch('/api/health')
11+
const { data } = await $fetchRaw('/api/health')
1212
expect(data).toMatchInlineSnapshot(`
1313
{
1414
"ok": true,
@@ -17,7 +17,7 @@ describe('routes', async () => {
1717
})
1818

1919
it('should return custom environment variables', async () => {
20-
const { data } = await $fetch('/api/env')
20+
const { data } = await $fetchRaw('/api/env')
2121
expect(data).toMatchInlineSnapshot(`
2222
{
2323
"isDev": true,

0 commit comments

Comments
 (0)