#How to test Nitro/H3?

2 messages · Page 1 of 1 (latest)

cloud bayBOT
#

Hi @smoky shuttle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To test Nitro/H3 endpoints in Nuxt, there are a couple of recommended approaches:

  1. Using the registerEndpoint helper:

The Nuxt documentation provides a registerEndpoint helper specifically for testing purposes. This allows you to create mock Nitro endpoints that return mocked data. Here's an example:

import { registerEndpoint } from '@nuxt/test-utils/runtime'

registerEndpoint('/test/', () => ({
  test: 'test-field'
}))

This method is particularly useful when you want to test components that make API requests to display data.

Nuxt Documentation (https://nuxt.com/docs/getting-started/testing#registerendpoint)

  1. Using the H3 Plain Adapter:

For more direct testing of H3 handlers, you can use the H3 Plain Adapter. This adapter provides an object input/output interface that's useful for testing your server or running in lambda-like environments. Here's an example:

import { toPlainHandler } from "h3";
import { app } from "./app.mjs";

const handler = toPlainHandler(app);

const response = await handler({
  method: "GET",
  path: "/",
  headers: {
    "x-test": "test",
  },
  body: undefined,
  context: {},
});

This approach allows you to directly test your H3 handlers without the need for a full HTTP server.

H3 Documentation - Plain Adapter (https://h3.unjs.io/adapters/plain)

Both of these methods provide ways to test your Nitro/H3 endpoints without the need for a full server setup, making them suitable for unit and integration testing scenarios.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: