Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🧪 Testing environment and utilities for Nitro

License

NotificationsYou must be signed in to change notification settings

johannschopplich/nitro-test-utils

Repository files navigation

The main goal for this package is to provide a simple and easy-to-use testing environment forNitro applications, built on top ofVitest. Use it to write tests for API routes and event handlers.

Features

  • 🚀 Automatic Nitro build (development or production mode)
  • ↪️ Reruns tests whenever Nitro source files change
  • 🥜 Run Nitro per test suite or globally
  • ✅ Seamless integration with Vitest
  • 🪝 Conditional code execution based on test mode (import.meta.test)
  • 📡 Familiar$fetchRaw helper similar to Nuxt test utils

Installation

Add thenitro-test-utils as well asvitest to your project with your favorite package manager:

# pnpmpnpm add -D nitro-test-utils vitest# npmnpm install -D nitro-test-utils vitest# yarnyarn add -D nitro-test-utils vitest

Basic Usage

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.

Global Nitro Build

Getting started with the global Nitro test environment for Vitest is as simple as creating a newvitest.config.ts configuration file in your project root. Set theglobal option totrue, which expectes the Nitro source files to be located in the working directory. See theConfiguration section for more options.

import{defineConfig}from'nitro-test-utils/config'exportdefaultdefineConfig({nitro:{global:true}})

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. atests 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:

import{$fetchRaw}from'nitro-test-utils/e2e'import{describe,expect,it}from'vitest'describe('api',()=>{it('responds successfully',async()=>{const{ data, status}=await$fetchRaw('/api/health')expect(status).toBe(200)expect(data).toMatchSnapshot()})})

Note

Whenever Nitro is rebuilt, the tests will rerun automatically (unless you have set themode option toproduction in the Vitest configuration).

Per Test Suite Nitro Build

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 newvitest.config.ts configuration file in your project root:

import{defineConfig}from'nitro-test-utils/config'exportdefaultdefineConfig()

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

Use thenitro-test-utils/e2e module to import thesetup function and the$fetchRaw helper. Thesetup function accepts an options object with therootDir property, which should point to the directory where the Nitro server is located. For more options, see theConfiguration section.

import{fileURLToPath}from'node:url'import{$fetchRaw,setup}from'nitro-test-utils/e2e'import{describe,expect,it}from'vitest'describe('api',async()=>{awaitsetup({rootDir:fileURLToPath(newURL('fixture',import.meta.url)),})it('responds successfully',async()=>{const{ data, status}=await$fetchRaw('/api/health')expect(status).toBe(200)expect(data).toMatchSnapshot()})})

Detecting Test Environment

You can detect whether your code is running in a Nitro build during tests by checking theimport.meta.test property. This is useful if you want to conditionally run code only in Nitro tests, but not in production.

exportdefaultdefineEventHandler(()=>{// Mock data for testsif(import.meta.test){return{foo:'bar'}}// Your production code hereconstdb=awaitconnectToDatabase()returndb.query()})

Custom Test Environment Variables

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.

# .env.testFOO=bar

Configuration

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 indevelopment 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.

Global Nitro Configuration

Global Nitro Root Directory

If your Nitro server is located in a different directory than the working directory, you can specify therootDir option in the Nitro configuration. It should point to the the same path where thenitro.config.ts file is located.

// vitest.config.tsimport{defineConfig}from'nitro-test-utils/config'exportdefaultdefineConfig({nitro:{global:{// Set the root directory of your Nitro serverrootDir:'backend'}},})

By default, the Vitest working directory is used.

Global Development vs. Production Build

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 themode option in the Vitest configuration:

// vitest.config.tsimport{defineConfig}from'nitro-test-utils/config'exportdefaultdefineConfig({nitro:{global:{mode:'production'},},})

Per Test Suite Nitro Configuration

Test Nitro Root Directory

If your Nitro server is located in a different directory than the working directory, you can specify therootDir option in thesetup function. It should point to the the same path where thenitro.config.ts file is located.

// tests/api.test.tsimport{fileURLToPath}from'node:url'import{setup}from'nitro-test-utils/e2e'describe('api',async()=>{awaitsetup({rootDir:fileURLToPath(newURL('fixture',import.meta.url)),})})

Test Development vs. Production Build

By default, the Nitro server is started in development mode. If you want to test your Nitro server in production mode, you can set themode option in thesetup function:

// tests/api.test.tsimport{fileURLToPath}from'node:url'import{setup}from'nitro-test-utils/e2e'describe('api',async()=>{awaitsetup({rootDir:fileURLToPath(newURL('fixture',import.meta.url)),mode:'production'})})

Test Utilities

injectServerUrl

To get the URL of the active test server for the current test suite or global test environment, you can use theinjectServerUrl function.

Usage:

import{injectServerUrl}from'nitro-test-utils/e2e'describe('api',()=>{it('should log the Nitro server URL',async()=>{constserverUrl=injectServerUrl()console.log(serverUrl)// http://localhost:3000})})

Type Declaration:

functioninjectServerUrl():string

createFetch

Creates a customofetch 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:

import{createFetch}from'nitro-test-utils/e2e'const$fetch=createFetch()

Type Declaration:

functioncreateFetch():$Fetch

$fetchRaw

The$fetchRaw function is a simple wrapper around the customofetch$Fetch instance created bycreateFetch. It simplifies requesting data from your Nitro server during testing. Import the function from thenitro-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 fromofetch.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:

// Use `data` instead of `body` for the parsed response bodyconst{ data, status, headers}=await$fetchRaw('/api/hello')expect(status).toBe(200)expect(data).toMatchSnapshot()

Type Declaration:

interfaceTestFetchResponse<T>extendsFetchResponse<T>{/** Alias for `response._data` */data?:T}function$fetchRaw<T=any,RextendsResponseType='json'>(path:string,options?:FetchOptions<R>):Promise<TestFetchResponse<MappedResponseType<R,T>>>

Tip

All additional options set increateFetch 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.

Migration

From v0.8 to v0.9

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:

-import { $fetch } from '../src/e2e'+import { $fetchRaw } from '../src/e2e'describe('api', async () => {  it('should respond data', async () => {-    const { status } = await $fetch('/')+    const { status } = await $fetchRaw('/')    expect(status).toBe(200)  })})

From v0.7 to v0.8

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 theglobal option to the Nitro configuration in thevitest.config.ts file:

import { defineConfig } from 'nitro-test-utils/config'export default defineConfig({  nitro: {+    global: true  }})

License

MIT License © 2024-PRESENTJohann Schopplich

About

🧪 Testing environment and utilities for Nitro

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp