Testing
MiiaJS provides a TestApp class for writing unit and integration tests. Import it from @miiajs/testing.
TestApp API
import { TestApp } from '@miiajs/testing'
const app = await TestApp.create(AppModule)
.override(UserService, mockUserService)
.compile()
Builder methods
| Method | Description |
|---|---|
TestApp.create(...modules) | Create a test app from modules |
.provide(...providers) | Add additional providers |
.override(token, value) | Replace a provider with a mock - a partial object of the token's type, or a function that returns one - or a configured module with another configuration (see Overrides) |
.use(...middlewares) | Add middleware |
.useGuard(...guards) | Add guards |
.setGlobalPrefix(prefix) | Mount every route under a path prefix (see Routing → Global prefix) |
.compile() | Build the test app (returns Promise<TestApp>) |
The builder methods only collect configuration - the order you call them in does not matter. compile() builds the app from all of it in one go: a new Miia with the global prefix, then providers, middleware, guards, the modules together with the overrides, and init(). Any builder method called after compile(), a second compile() included, throws.
Instance methods
| Method | Description |
|---|---|
.request(method, path, options?) | Send an HTTP request |
.resolve(token) | Resolve a provider from the container - any token, not checked against module boundaries |
.close() | Clean up resources |
The instance methods need a compiled app and throw [Miia] TestApp: call compile() first before it.
Overrides
An override is passed to the app next to the modules and replaces exactly one entry while the module graph loads, so it does not matter which module declares the token or in what order the modules come. It works on:
- a provider a loaded module declares - in
providers, or in the providers of aconfigure()call (drizzleDb(), model tokens); - a feature config from
ConfigModule.register(), like any provider:.override(paymentsConfig, { STRIPE_KEY: 'test' })- its schema does not run; - a token registered with
.provide(), and the built-insDiscoveryServiceandResolver- an overriddenResolveris one fixed fake that every module gets, instead of a resolver bound to each module; - a configured module:
.override(ConfigModule, ConfigModule.configure(testOptions))replaces theConfigModule.configure(...)the graph imports, wherever it is imported.
const app = await TestApp.create(AppModule)
.override(ConfigModule, ConfigModule.configure({ schema: envSchema, env: { DATABASE_URL: 'postgres://test' } }))
.override(UserService, mockUserService)
.compile()
REQUEST_CONTEXT is not an override target: every request seeds its own, so .override(REQUEST_CONTEXT, ...) (and .provide() of it) throws on compile(). Test a request-scoped provider through a route with .request(), or override that provider itself.
An override that matches nothing in the loaded graph throws on compile(): a token no loaded module provides ([Miia] override(X): no loaded module provides X - use provide() for a module-less test), or a module the graph never configures. Guards - on a route through @UseGuard() or global through .useGuard() - and controllers are replaced only when they are declared in the providers / controllers of a loaded module; a guard that is constructed on first use and declared nowhere cannot be overridden, so add it to providers (and to exports when controllers of other modules use it - see Guards and modules).
A plain-object override has no class, so DiscoveryService does not see it: an @On handler replaced with { onCreated() {} } is not subscribed, and a controller replaced that way still answers requests but drops out of the Swagger spec. To keep it discoverable, override with an instance of a named subclass that has no decorators of its own. The consumer group and the default Swagger tag then come from the subclass name (an anonymous class extends has an empty one):
class FakeOrderHandlers extends OrderHandlers {
override async onCreated() {}
}
const app = await TestApp.create(AppModule).override(OrderHandlers, new FakeOrderHandlers()).compile()
A named package module is replaced the same way, by its class and a configuration with the same name; the default connection stays as the graph configures it:
const app = await TestApp.create(AppModule)
.override(DrizzleModule, DrizzleModule.configure(testAnalyticsOptions, { name: 'analytics' }))
.compile()
The replacement inherits global from the configuration it replaces, so leave global out of it. A replacement that sets a different global throws: [Miia] override(ConfigModule): the replacement sets global: true, but the configured module it replaces does not - leave global out, it is inherited.
Integration tests
Test your HTTP endpoints end-to-end:
import { describe, it, expect, beforeAll, afterAll } from 'bun:test'
import { TestApp } from '@miiajs/testing'
import { AppModule } from '../src/app.module.js'
describe('UserController', () => {
let app: TestApp
beforeAll(async () => {
app = await TestApp.create(AppModule)
.override(UserService, {
findAll: () => [{ id: 1, name: 'Alice' }],
create: (data) => ({ id: 2, ...data }),
})
.compile()
})
afterAll(() => app.close())
it('GET /users should return users', async () => {
const res = await app.request('GET', '/users')
expect(res.status).toBe(200)
expect(await res.json()).toEqual([{ id: 1, name: 'Alice' }])
})
it('POST /users should create a user', async () => {
const res = await app.request('POST', '/users', {
body: { name: 'Bob', email: '[email protected]' },
})
expect(res.status).toBe(201)
expect(await res.json()).toMatchObject({ name: 'Bob' })
})
it('POST /users should validate body', async () => {
const res = await app.request('POST', '/users', {
body: { invalid: true },
})
expect(res.status).toBe(422)
})
})
Unit tests
Test individual services with mocked dependencies:
describe('UserService', () => {
let app: TestApp
let service: UserService
beforeAll(async () => {
app = await TestApp.create()
.provide(UserService, {
token: DatabaseService,
factory: () => ({ query: () => [{ id: 1, name: 'Alice' }] }),
})
.compile()
service = app.resolve(UserService)
})
afterAll(() => app.close())
it('should find all users', async () => {
const result = await service.findAll()
expect(result).toEqual([{ id: 1, name: 'Alice' }])
})
})
Request options
The request() method accepts an options object:
const res = await app.request('POST', '/api/users', {
body: { name: 'Alice' },
headers: {
'Authorization': 'Bearer my-token',
'X-Custom': 'value',
},
query: {
page: '1',
limit: '10',
},
ip: '10.0.0.1',
})
| Option | Type | Description |
|---|---|---|
body | any | Request body (auto-serialized to JSON) |
headers | Record<string, string> | Request headers |
query | Record<string, string> | Query parameters |
ip | string | Fake client address - the handler sees it as ctx.ip / ctx.conn.remoteAddress (useful for rate-limit tests) |
Testing with auth
import { JwtService } from '@miiajs/jwt'
describe('Protected routes', () => {
let app: TestApp
let token: string
beforeAll(async () => {
app = await TestApp.create(AppModule)
.override(UserService, mockUserService)
.compile()
const jwt = app.resolve(JwtService)
token = await jwt.sign({ sub: '1', role: 'admin' })
})
it('should reject unauthenticated requests', async () => {
const res = await app.request('GET', '/api/users/1')
expect(res.status).toBe(401)
})
it('should allow authenticated requests', async () => {
const res = await app.request('GET', '/api/users/1', {
headers: { Authorization: `Bearer ${token}` },
})
expect(res.status).toBe(200)
})
})