Gathering detailed insights and metrics for nitro-test-utils
Gathering detailed insights and metrics for nitro-test-utils
Gathering detailed insights and metrics for nitro-test-utils
Gathering detailed insights and metrics for nitro-test-utils
npm install nitro-test-utils
Typescript
Module System
Node Version
NPM Version
TypeScript (98.86%)
JavaScript (1.14%)
Total Downloads
58,340
Last Day
117
Last Week
2,354
Last Month
9,426
Last Year
57,367
MIT License
91 Stars
82 Commits
3 Forks
2 Watchers
1 Branches
4 Contributors
Updated on Jun 20, 2025
Latest Version
0.9.2
Package Id
nitro-test-utils@0.9.2
Unpacked Size
30.71 kB
Size
8.23 kB
File Count
18
NPM Version
10.9.2
Node Version
22.14.0
Published on
Apr 02, 2025
Cumulative downloads
Total Downloads
Last Day
216.2%
117
Compared to previous day
Last Week
-1.3%
2,354
Compared to previous week
Last Month
-1.9%
9,426
Compared to previous month
Last Year
5,795.9%
57,367
Compared to previous year
The main goal for this package is to provide a simple and easy-to-use testing environment for Nitro applications, built on top of Vitest. Use it to write tests for API routes and event handlers.
import.meta.test
)$fetchRaw
helper similar to Nuxt test utilsAdd the nitro-test-utils
as well as vitest
to your project with your favorite package manager:
1# pnpm 2pnpm add -D nitro-test-utils vitest 3 4# npm 5npm install -D nitro-test-utils vitest 6 7# yarn 8yarn add -D nitro-test-utils vitest
There are two ways to set up the Nitro test environment: globally or per test suite. The global setup is useful if you want to test multiple test files against the same Nitro server. The per test suite setup is useful if you want to test different Nitro servers in different test files.
[!TIP] The global setup is recommended for most use cases where only one Nitro application is being developed. It is more convenient to use than the per-test-suite setup because it keeps the Nitro development server running in the background (localhost:3000 by default) during Vitest watch mode. This allows you to develop your Nitro application and write tests at the same time.
Getting started with the global Nitro test environment for Vitest is as simple as creating a new vitest.config.ts
configuration file in your project root. Set the global
option to true
, which expectes the Nitro source files to be located in the working directory. See the Configuration section for more options.
1import { defineConfig } from 'nitro-test-utils/config' 2 3export default defineConfig({ 4 nitro: { 5 global: true 6 } 7})
[!TIP] Under the hood, Vitest will automatically spin up a Nitro server before running your tests and shut it down afterwards.
Write your tests in a dedicated location, e.g. a tests
directory. You can use the $fetch
function to make requests to the Nitro server that is started by the test environment.
A simple teste case could look like this:
1import { $fetchRaw } from 'nitro-test-utils/e2e' 2import { describe, expect, it } from 'vitest' 3 4describe('api', () => { 5 it('responds successfully', async () => { 6 const { data, status } = await $fetchRaw('/api/health') 7 8 expect(status).toBe(200) 9 expect(data).toMatchSnapshot() 10 }) 11})
[!NOTE] Whenever Nitro is rebuilt, the tests will rerun automatically (unless you have set the
mode
option toproduction
in the Vitest configuration).
For multiple Nitro servers as part of your project, you can set up the Nitro test environment per test suite. Configure Vitest by creating a new vitest.config.ts
configuration file in your project root:
1import { defineConfig } from 'nitro-test-utils/config' 2 3export default defineConfig()
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.
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 section.
1import { fileURLToPath } from 'node:url' 2import { $fetchRaw, setup } from 'nitro-test-utils/e2e' 3import { describe, expect, it } from 'vitest' 4 5describe('api', async () => { 6 await setup({ 7 rootDir: fileURLToPath(new URL('fixture', import.meta.url)), 8 }) 9 10 it('responds successfully', async () => { 11 const { data, status } = await $fetchRaw('/api/health') 12 13 expect(status).toBe(200) 14 expect(data).toMatchSnapshot() 15 }) 16})
You can detect whether your code is running in a Nitro build during tests by checking the import.meta.test
property. This is useful if you want to conditionally run code only in Nitro tests, but not in production.
1export default defineEventHandler(() => { 2 // Mock data for tests 3 if (import.meta.test) { 4 return { foo: 'bar' } 5 } 6 7 // Your production code here 8 const db = await connectToDatabase() 9 return db.query() 10})
You can set custom environment variables for your tests by creating a .env.test
file in your Nitro project root. The variables will be loaded automatically when the Nitro server is started.
1# .env.test 2FOO=bar
Depending of your use case, you can configure the Nitro test environment globally or per test suite.
[!NOTE] In each case, you can build Nitro in
development
orproduction
mode. If the mode is set todevelopment
, the presetnitro-dev
will be used. Otherwise, Nitro will is built with thenode
preset. You cannot set the Nitro build preset, since only builds for Node.js are supported in Vitest.
If your Nitro server is located in a different directory than the working directory, you can specify the rootDir
option in the Nitro configuration. It should point to the the same path where the nitro.config.ts
file is located.
1// vitest.config.ts
2import { defineConfig } from 'nitro-test-utils/config'
3
4export default defineConfig({
5 nitro: {
6 global: {
7 // Set the root directory of your Nitro server
8 rootDir: 'backend'
9 }
10 },
11})
By default, the Vitest working directory is used.
By default, the Nitro server starts in development mode. This makes development easier, as Nitro will automatically reload when you make changes to your code and the tests will also automatically re-run.
To test the production build of your Nitro server, set the mode
option in the Vitest configuration:
1// vitest.config.ts 2import { defineConfig } from 'nitro-test-utils/config' 3 4export default defineConfig({ 5 nitro: { 6 global: { 7 mode: 'production' 8 }, 9 }, 10})
If your Nitro server is located in a different directory than the working directory, you can specify the rootDir
option in the setup
function. It should point to the the same path where the nitro.config.ts
file is located.
1// tests/api.test.ts 2import { fileURLToPath } from 'node:url' 3import { setup } from 'nitro-test-utils/e2e' 4 5describe('api', async () => { 6 await setup({ 7 rootDir: fileURLToPath(new URL('fixture', import.meta.url)), 8 }) 9})
By default, the Nitro server is started in development mode. If you want to test your Nitro server in production mode, you can set the mode
option in the setup
function:
1// tests/api.test.ts 2import { fileURLToPath } from 'node:url' 3import { setup } from 'nitro-test-utils/e2e' 4 5describe('api', async () => { 6 await setup({ 7 rootDir: fileURLToPath(new URL('fixture', import.meta.url)), 8 mode: 'production' 9 }) 10})
injectServerUrl
To get the URL of the active test server for the current test suite or global test environment, you can use the injectServerUrl
function.
Usage:
1import { injectServerUrl } from 'nitro-test-utils/e2e' 2 3describe('api', () => { 4 it('should log the Nitro server URL', async () => { 5 const serverUrl = injectServerUrl() 6 console.log(serverUrl) // http://localhost:3000 7 }) 8})
Type Declaration:
1function injectServerUrl(): string
createFetch
Creates a custom ofetch
instance with the Nitro server URL as the base URL.
[!TIP] The following additional fetch options have been set as defaults:
ignoreResponseError: true
to prevent throwing errors on non-2xx responses.redirect: 'manual'
to prevent automatic redirects.headers: { accept: 'application/json' }
to force a JSON error response when Nitro returns an error.
Usage:
Inside a test case:
1import { createFetch } from 'nitro-test-utils/e2e' 2 3const $fetch = createFetch()
Type Declaration:
1function createFetch(): $Fetch
$fetchRaw
The $fetchRaw
function is a simple wrapper around the custom 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.
$fetchRaw
returns a promise that resolves with the raw response from ofetch.raw
. This is useful because it allows you to access the response status code, headers, and body, even if the response failed.
Usage:
Inside a test case:
1// Use `data` instead of `body` for the parsed response body 2const { data, status, headers } = await $fetchRaw('/api/hello') 3 4expect(status).toBe(200) 5expect(data).toMatchSnapshot()
Type Declaration:
1interface TestFetchResponse<T> extends FetchResponse<T> { 2 /** Alias for `response._data` */ 3 data?: T 4} 5 6function $fetchRaw<T = any, R extends ResponseType = 'json'>( 7 path: string, 8 options?: FetchOptions<R> 9): Promise<TestFetchResponse<MappedResponseType<R, T>>>
[!TIP] All additional options set in
createFetch
apply here as well, sucg hasignoreResponseError
set totrue
to prevent the function from throwing an error when the response status code is not in the range of 200-299.
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.
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:
1-import { $fetch } from '../src/e2e' 2+import { $fetchRaw } from '../src/e2e' 3 4describe('api', async () => { 5 it('should respond data', async () => { 6- const { status } = await $fetch('/') 7+ const { status } = await $fetchRaw('/') 8 expect(status).toBe(200) 9 }) 10})
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:
1import { defineConfig } from 'nitro-test-utils/config' 2 3export default defineConfig({ 4 nitro: { 5+ global: true 6 } 7})
MIT License © 2024-PRESENT Johann Schopplich
No vulnerabilities found.
No security vulnerabilities found.