Giter Club home page Giter Club logo

nitro-test-utils's Introduction

Nitro Test Utils

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.

Features

  • ๐Ÿš€ Automatic Nitro server start and stop
  • โ†ช๏ธ Reruns tests whenever Nitro is rebuilt
  • โœ… Seamless integration with Vitest
  • ๐Ÿช Detect test mode with import.meta.test
  • ๐Ÿ“ก Familiar $fetch helper like Nuxt test utils

Installation

Add the nitro-test-utils as well as vitest to your project with your favorite package manager:

# pnpm
pnpm add -D nitro-test-utils vitest

# npm
npm install -D nitro-test-utils vitest

# yarn
yarn add -D nitro-test-utils vitest

Basic Usage

Setting up the Nitro test environment for Vitest is as simple as creating a new vitest.config.ts configuration file in your project root.

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

export default defineConfig({})

Tip

Under the hood, the defineConfig function will automatically spin up a Nitro server in development mode 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 example could look like this:

// `test/routes.test.ts`
import { describe, expect, it } from 'vitest'
import { $fetch } from 'nitro-test-utils/e2e'

describe('routes', () => {
  it('responds successfully', async () => {
    const { data, status } = await $fetch('/api/health')

    expect(status).toBe(200)
    expect(data).toMatchSnapshot()
  })
})

Note

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

Detecting Test Mode

You can detect whether your code is running in test mode by checking the import.meta.test property. This is useful if you want to conditionally run code only in test mode, but not in production.

// `routes/api/my-handler.ts`
export default defineEventHandler(() => ({
  isTest: import.meta.test,
}))

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.test
FOO=bar

Configuration

Nitro Root Directory

If your Nitro server is located in a different directory, you can specify the rootDir option in the Nitro configuration. It should be the path where the nitro.config.ts file lives.

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

export default defineConfig({
  nitro: {
    // Set the root directory of your Nitro app
    rootDir: 'server',
  },
})

By default, the Vitest working directory is used.

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

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

export default defineConfig({
  nitro: {
    mode: 'production',
  },
})

Test Utilities

$fetch

The $fetch function is a simple wrapper around 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.

$fetch 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 definition:

// Use `data` instead of `body` for the parsed response body
const { data, status, headers } = await $fetch('/api/hello')

expect(status).toBe(200)
expect(data).toMatchSnapshot()

Type Declaration:

function $fetch<T = any, R extends ResponseType = 'json'>(
  path: string,
  options?: FetchOptions<R>
): Promise<FetchResponse<MappedResponseType<R, T>>>

Tip

Fetch options will be merged with sensible default options, like ignoreResponseError set to true to prevent the function from throwing an error when the response status code is not in the range of 200-299.

Roadmap

As of right now, the following features are planned:

  • Make environment setup work within Nuxt projects

License

MIT License ยฉ 2024-PRESENT Johann Schopplich

nitro-test-utils's People

Contributors

johannschopplich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nitro-test-utils's Issues

Support Nuxt 3

Hey, I know that support for Nuxt 3 is planned. Is there currently any workarounds to make it work with Nuxt?

I think that it may be just the nuxt plugins that don't work:

[worker reload] ReferenceError: defineNuxtPlugin is not defined
    at file:///Users/alex/listings-papmeq/.output/.nitro/dev/index.mjs:616:21
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12)
stdout | tests/auth/login.test.ts > routes > responds successfully

Thank you! Great library btw. Super useful

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.