Pure In-Memory Testing & TestKit¶
Katal v3 provides a high-speed Pure In-Memory Testing Model. Because Katal adheres to Web Standards (Request, Response, Headers), your entire HTTP pipeline, onion middleware stack, validation, controllers, and dependency injection execute directly in memory with zero TCP socket allocation, resulting in 50x faster test execution.
1. Direct In-Memory Dispatch (app.handle)¶
The fastest way to test routes is passing standard Web Request objects directly to app.handle():
import { Application, Controller } from "katal";
import type { RequestContext } from "katal";
import { describe, it, expect } from "bun:test"; // Or vitest / jest
describe("User API", () => {
const app = new Application();
class UserController extends Controller {
async handle(ctx: RequestContext) {
return this.success({ id: ctx.params.id, name: "Alice" });
}
}
app.getRouter().get("/api/users/:id", UserController);
it("returns user details by ID in memory with 0ms TCP latency", async () => {
// Dispatched directly through onion middleware & router in memory!
const response = await app.handle(new Request("http://localhost/api/users/42"));
expect(response.status).toBe(200);
const body = await response.json();
expect(body.data).toEqual({ id: "42", name: "Alice" });
});
});
2. Fluent Laravel-Style Assertions (RequestClient)¶
For expressive, fluent test assertions without boilerplate expect checks, wrap your app in AppFactory.createTestClient(app):
import { Application, Controller } from "katal";
import { AppFactory } from "katal/testing";
import { describe, it } from "bun:test";
import { z } from "zod";
describe("E-Commerce Products API", () => {
const app = new Application();
const client = AppFactory.createTestClient(app);
const productSchema = z.object({
name: z.string().min(2),
price: z.number().positive(),
});
class CreateProductController extends Controller {
static schema = { body: productSchema };
async handle(ctx) {
return this.created({ id: "prod-99", ...ctx.body });
}
}
app.getRouter().post("/api/products", CreateProductController);
it("creates a product and asserts JSON structure fluently", async () => {
const response = await client.post("/api/products", {
name: "Mechanical Keyboard",
price: 129.99,
});
// Fluent assertion chain
response
.assertStatus(201)
.assertHeader("Content-Type", "application/json")
.assertJson({
data: {
id: "prod-99",
name: "Mechanical Keyboard",
price: 129.99,
},
});
});
it("returns 422 Problem Details when payload validation fails", async () => {
const response = await client.post("/api/products", {
name: "A", // Violates min(2)
price: -10, // Violates positive()
});
response
.assertStatus(422)
.assertHeader("Content-Type", "application/problem+json")
.assertJsonPath("title", "Validation Failed");
});
});
Supported Assertion Methods¶
| Method | Description |
|---|---|
.assertStatus(code) |
Asserts that HTTP status code matches code. |
.assertHeader(key, value) |
Asserts that response header matches expected value or pattern. |
.assertJson(partial) |
Deeply asserts that response JSON contains subset matching partial. |
.assertExactJson(exact) |
Asserts that response JSON matches exact with identical keys. |
.assertJsonPath(path, val) |
Asserts that dot-notation path (e.g. 'errors.email[0]') matches val. |
3. Isolated Controller Unit Testing (Zero Server Overhead)¶
Because Katal controllers accept a monomorphic RequestContext instance, you can test complex controller logic in total isolation without booting Application or mounting routes:
import { describe, it, expect } from "bun:test";
import { RequestContext } from "katal";
import { TransferFundsController } from "./TransferFundsController";
describe("TransferFundsController Unit Test", () => {
it("transfers funds between accounts with mocked bank service", async () => {
// 1. Mock dependencies
const mockBankService = {
transfer: async (from: string, to: string, amount: number) => true,
};
// 2. Instantiate controller directly with mocked dependency
const controller = new TransferFundsController(mockBankService as any);
// 3. Create standalone RequestContext instance
const ctx = new RequestContext(
new Request("http://localhost/api/transfer", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ from: "acc-1", to: "acc-2", amount: 500 }),
})
);
ctx.setValidated("body", { from: "acc-1", to: "acc-2", amount: 500 });
// 4. Execute handle directly
const response = await controller.handle(ctx);
expect(response.status).toBe(200);
const data = await response.json();
expect(data.data.success).toBe(true);
});
});
4. Mocking Services in the IoC Container¶
Override registered singletons with mock implementations in test fixtures:
import { Application } from "katal";
import { PaymentGateway } from "./services/PaymentGateway";
const app = new Application();
// Replace real Stripe gateway with an in-memory test double
const mockGateway = {
charge: async (token: string, amount: number) => ({ id: "ch_test_123", paid: true }),
};
app.getContainer().instance(PaymentGateway, mockGateway);
5. Synthetic JWT Testing with createTestToken¶
Generate valid test tokens instantly without calling login endpoints or provisioning database users:
import { createTestToken } from "katal/testing";
it("authorizes admin actions with synthetic test token", async () => {
// Generate signed token with user payload
const token = await createTestToken({
id: "usr-admin-1",
email: "admin@enterprise.com",
role: "admin",
}, "super-secret-jwt-key");
const response = await app.handle(new Request("http://localhost/admin/audit-logs", {
headers: {
"Authorization": `Bearer ${token}`,
},
}));
expect(response.status).toBe(200);
});
6. Deterministic Time Testing with FakeClock¶
Control wall-clock time for testing sliding-window rate limit resets, token expirations, and delayed queue jobs:
import { FakeClock } from "katal/testing";
describe("Token Expiration Check", () => {
it("rejects token after TTL has elapsed", async () => {
const clock = new FakeClock(new Date("2026-01-01T12:00:00Z"));
// Advance virtual time by 2 hours
clock.advance(2 * 60 * 60 * 1000);
expect(clock.now().toISOString()).toBe("2026-01-01T14:00:00.000Z");
});
});