#How to test Nitro/H3?
2 messages · Page 1 of 1 (latest)
To test Nitro/H3 endpoints in Nuxt, there are a couple of recommended approaches:
- Using the
registerEndpointhelper:
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)
- 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)