Testing (inject)

SpaceNode provides app.inject() to simulate HTTP requests without starting a real server. Perfect for unit and integration tests.

Basic Usage

import { createApp } from 'SpaceNode'

const app = await createApp()

// Simulate a GET request
const res = await app.inject({
  method: 'GET',
  url: '/users',
})

console.log(res.statusCode)  // 200
console.log(res.json)        // [{ id: 1, name: "John" }]
console.log(res.headers)     // { 'content-type': '...' }
console.log(res.body)        // raw string

Inject Options

OptionTypeDefaultDescription
methodstring'GET'HTTP method
urlstring'/'URL path with optional query string
headersobject{}Request headers
bodyanynullRequest body (objects auto-serialized to JSON)

Response Object

PropertyTypeDescription
statusCodenumberHTTP status code
headersobjectResponse headers
bodystringResponse body as string
jsonany|nullParsed JSON body, or null

POST with Body

const res = await app.inject({
  method: 'POST',
  url: '/auth/login',
  body: {
    email: 'john@mail.com',
    password: 'secret123',
  },
})

console.log(res.statusCode)  // 200
console.log(res.json.token)  // "eyJ..."

With Auth Headers

const res = await app.inject({
  method: 'GET',
  url: '/auth/me',
  headers: {
    Authorization: 'Bearer eyJ...',
  },
})

console.log(res.json.user)  // { id: 1, name: "John" }

With Node.js Test Runner

import { test } from 'node:test'
import assert from 'node:assert'
import { createApp } from 'SpaceNode'

test('GET /health returns 200', async () => {
  const app = await createApp()
  app.setRoute('GET', '/health', ({ send }) => send({ ok: true }))

  const res = await app.inject({ url: '/health' })

  assert.strictEqual(res.statusCode, 200)
  assert.deepStrictEqual(res.json, { ok: true })
})

test('POST /users validates body', async () => {
  const app = await createApp()

  const res = await app.inject({
    method: 'POST',
    url: '/users',
    body: { name: '' },  // invalid
  })

  assert.strictEqual(res.statusCode, 400)
})
No server neededinject() does not open a port. It pipes directly through the request pipeline. Tests are fast and don't require port management.

With setRoute()

Combine setRoute() + inject() for express-like test patterns:

const app = await createApp({ modulesDir: './_none' })

app.setRoute('GET', '/hello/:name', ({ params, send }) => {
  send({ greeting: `Hello, ${params.name}!` })
})

const res = await app.inject({ url: '/hello/World' })
console.log(res.json.greeting)  // "Hello, World!"