12 · Engineering Patterns
Testing & Mocking
Testing with dn-ioc doesn't require vi.mock(), mock.module(), or brittle afterEach(() => container.reset()) rituals. Because there's no global container, every bootstrapApp() call builds a fresh, isolated dependency graph in memory—so dozens of test files can run concurrently without stepping on each other, and provideFor() swaps any Token<T> or Ref<T> in one line.
1export const testOrderSubmitUnit = async () => {2 const sent: string[] = []34 const fakeOrders = (): OrderRepository => ({5 find: async id => ({ id, customerEmail: 'ada@example.com', status: 'draft' }),6 save: async () => undefined,7 })89 const fakeMailer = (): Mailer => ({10 sendOrderConfirmation: async (email, id) => {11 sent.push(`${email}:${id}`)12 },13 })1415 // Unit test: install only fakes — a forgotten token rejects start() immediately16 await using app = bootstrapApp(17 async ({ inject }) => {18 const order = await inject(orderServiceRef).submit('ord-unit')19 console.log(order.status, sent.length) // submitted 120 },21 {22 providers: [23 provideFor(orderRepositoryToken, fakeOrders),24 provideFor(clockToken, () => ({ now: () => new Date('2026-11-18T00:00:00Z') })),25 provideFor(mailerToken, fakeMailer),26 ],27 },28 )2930 await app.start()31} // app.stop() runs automatically when the scope exits
Unit Testing with Isolated Fakes
In a unit test, you instantiate a dedicated bootstrapApp() and install only the fakes the system under test needs (fakeOrders, a fixed Clock, and fakeMailer in order-service.unit.test.ts).
provideFor(key, fakeFactory) works identically whether key is a Token<T> or a Ref<T>, but what happens when you forget to mock a dependency depends on which kind of key you used:
| Key kind | If you forget provideFor() in a unit test | Practical impact |
|---|---|---|
Token<T> | Rejects app.start() immediately with No provider for token: Name. | Fails fast: a unit test can never accidentally open a real socket or send a real email. |
Ref<T> | Not an error—self-installs and runs the Ref's real factory. | Silent fallback: handy for pure in-memory helpers, risky if the unmocked Ref talks to external I/O. |
Compare the DDD unit test above with the MVC test (services/user-service.test.ts): swapping userRepositoryRef via provideFor(userRepositoryRef, fakeUserRepository) is just as clean, as long as you remember to override every I/O-touching Ref that userServiceRef reaches.
1import { bootstrapApp, provideFor } from 'dn-ioc'2import type { User } from './models/user'3import { userRepositoryRef } from './repositories/user-repository'4import { userServiceRef } from './services/user-service'56const stored = new Map<string, User>()78const fakeUserRepository = () => ({9 findByEmail: async (email: string) => stored.get(email),10 create: async (user: User) => {11 stored.set(user.email, user)12 return user13 },14})1516export const testApp = bootstrapApp(17 async ({ inject }) => {18 const service = inject(userServiceRef)19 const created = await service.register('grace@example.com', 'Grace Hopper')20 console.log(created.email, stored.size) // grace@example.com 121 },22 {23 providers: [provideFor(userRepositoryRef, fakeUserRepository)],24 },25)2627await testApp.start()28await testApp.stop()
Integration Testing with Bundle Overrides
Unit tests prove your business logic works with fakes; integration tests prove your real SQL repositories, serialization, and domain services work together while stubbing out external third parties like SMTP or Stripe.
Because dn-ioc flattens arrays and ProviderBundles in source order—and later bindings in the same scope silently replace earlier ones—you can install your entire production infraProviders bundle first and override a single port right after it:
- Correct order (
[infraProviders, provideFor(mailerToken, fakeMailer)]): InstallssqlTableRef,sqlOrderRepositoryProvider,systemClockProvider, andsmtpMailerProvider, then replacesmailerTokenwithfakeMailer. - Wrong order (
[provideFor(mailerToken, fakeMailer), infraProviders]):infraProvidersflattens after your fake and silently overwritesmailerTokenback to the realsmtpMailerProvider!
1export interface SentMail {2 email: string3 orderId: string4}56export const testOrderSubmitIntegration = async () => {7 const outbox: SentMail[] = []8 const fakeMailer = (): Mailer => ({9 async sendOrderConfirmation(email, orderId) {10 outbox.push({ email, orderId })11 },12 })1314 // Integration test: list infraProviders first, then overrides after (last-write-wins)15 await using app = bootstrapApp(16 async ({ inject }) => {17 const order = await inject(orderServiceRef).submit('ord-1')18 console.log(order.status, outbox.length) // submitted 119 },20 {21 providers: [22 infraProviders,23 provideFor(mailerToken, fakeMailer),24 ],25 },26 )2728 await app.start()29} // app.stop() runs automatically when the scope exits
Per-Test Cleanup with await using
Notice await using app = bootstrapApp(...) in both testOrderSubmitUnit() and testOrderSubmitIntegration():
- Because
AppimplementsAsyncDisposable, TypeScript automatically awaitsapp.stop()when execution leaves the function block—even if anexpect()assertion throws halfway through the test. sqlTableRef'sonDisposehook runs before the test returns, closing pools, timers, or temporary servers cleanly with zerotry / finallyboilerplate.
If a codebase doesn't use await using yet, wrapping the test body in try { await app.start() } finally { await app.stop() } does the exact same job—and because app.stop() is idempotent, calling it twice in teardown hooks is always safe.
Need to check an exact type signature or look up an error message? Head into Part IV with the Public API Reference and Errors & Diagnostics.