dn-ioc

12 · 實戰架構模式

測試與替身模擬

用 dn-ioc 寫測試,完全唔使出動 vi.mock()、mock.module(),亦唔使每個檔案例牌寫句脆弱嘅 afterEach(() => container.reset())。事關全個程式庫根本冇全域 Container,每次呼叫 bootstrapApp() 都會喺記憶體入面起一張全新、完全隔離嘅依賴圖——幾十個測試檔案一齊並行開跑都唔會互相踩場,而且用 provideFor() 一行就可以換走任何 Token<T> 或 Ref<T>。

order-service.unit.test.ts
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

用獨立假實作跑單元測試

寫單元測試嗰陣,你只需要開一個專屬嘅 bootstrapApp(),然後淨係裝入受測目標需要嗰幾個假實作(好似 order-service.unit.test.ts 入面嘅 fakeOrders、固定時間嘅 Clock 同埋 fakeMailer)。

無論個 key 係 Token<T> 定係 Ref<T>,provideFor(key, fakeFactory) 嘅寫法都完全一樣;但萬一你唔記得 mock 某個依賴,兩者嘅後果就差好遠:

Key 種類單元測試漏寫 provideFor() 嗰陣實際影響
Token<T>app.start() 即刻 reject No provider for token: Name。即刻 Fail fast: 單元測試絕對唔可能唔小心連咗去真 socket 或者真係寄咗封電郵出去。
Ref<T>唔當係錯 —— 自動安裝兼執行嗰個 Ref 帶住嘅真實 factory。靜默行返真嘢: 對於純記憶體輔助工具好方便,但如果嗰個漏咗 mock 嘅 Ref 會掂外部 I/O 就有風險。

你可以將上面份 DDD 單元測試同下面份 MVC 測試(services/user-service.test.ts)拍埋一齊睇:用 provideFor(userRepositoryRef, fakeUserRepository) 換走 userRepositoryRef 一樣咁乾手淨腳,只要你記得將 userServiceRef 背後會掂到外部 I/O 嘅 Ref 全部換晒做假實作就冇問題。

services/user-service.test.ts
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()

整合測試:喺 Bundle 後面局部覆蓋

單元測試負責驗證業務邏輯配假實作行得通;整合測試就負責驗證真實嘅 SQL Repository、資料序列化同業務 Service 夾埋一齊真係夾得埋,同時將 SMTP 電郵或者 Stripe 扣數呢類外部第三方服務換成假替身。

因為 dn-ioc 會按源碼順序由左至右攤平陣列同 ProviderBundle,而且同一個 scope 入面寫喺後面嘅綁定會靜靜雞覆蓋前面嗰個,你可以先裝入成包正式環境用嘅 infraProviders,再緊貼喺佢後面覆蓋單一個 Port:

  • 正確次序([infraProviders, provideFor(mailerToken, fakeMailer)]): 先裝好 sqlTableRef、sqlOrderRepositoryProvider、systemClockProvider 同 smtpMailerProvider,跟住用 fakeMailer 換走 mailerToken。
  • 調轉咗次序([provideFor(mailerToken, fakeMailer), infraProviders]): infraProviders 喺你個假實作之後攤平,結果會無聲無息將 mailerToken 蓋返做真實嘅 smtpMailerProvider!呢個位千萬要睇清楚次序。
order-service.integration.test.ts
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

用 await using 幫每個測試自動清場

留意吓 testOrderSubmitUnit() 同 testOrderSubmitIntegration() 入面嗰句 await using app = bootstrapApp(...):

  • 因為 App 實作咗 AsyncDisposable,一離開個測試函式區塊,TypeScript 就會自動幫你 await app.stop()——就算跑到一半某句 expect() 斷言爆咗錯都照樣保證執行。
  • sqlTableRef 入面登記嘅 onDispose hook 會喺測試結束前乖乖跑完,自動閂好連線池、timer 或者臨時測試 server,連 try / finally 樣板碼都慳返。

如果你個專案環境暫時未開 await using,用傳統嘅 try { await app.start() } finally { await app.stop() } 包住測試內容效果完全一樣——而且因為 app.stop() 係冪等嘅,就算喺清理階段唔小心 call 多咗次都絕對安全。

想隨時翻查某個 API 嘅精準型別簽名,或者對照某條報錯原文搵解法?即刻揭去最後一部分:公開 API 參考手冊同埋錯誤訊息與排錯指南。