All files / src/testing test-container.mts

76.78% Statements 129/168
52.8% Branches 47/89
84.09% Functions 37/44
77.63% Lines 125/161

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600                                                                                                  21x 21x 21x 21x                                             21x 21x     21x 21x                                               13x 13x   13x   7x 7x     5x 5x     1x 1x                 1x 1x 1x 1x 1x                     3x 3x 3x 5x   3x 1x                   3x 3x 3x 3x   3x 1x                   1x 1x   1x           1x 1x                     1x 1x   1x           1x 1x                     1x 1x   1x           1x 1x                     1x 1x   1x                       1x 1x   1x                                                                                                                                               8x 8x 8x             8x                     7x 7x 7x         7x   7x 7x 7x               1x 1x 1x   1x                             1x 1x 1x 1x     1x                     1x 1x 3x   1x                     2x 2x             2x 2x                     1x                       1x 1x 1x   1x 3x 3x   3x                 3x 3x       1x               1x 1x   1x 2x 2x   2x 2x     2x                   1x 2x     1x               44x 7x   37x     37x               7x           7x                 7x 7x           7x 7x             5x                           1x 1x   1x       1x                   1x     1x 1x 1x     1x        
import type {
  BindingBuilder,
  DependencyGraph,
  DependencyNode,
  LifecycleRecord,
  MethodCallRecord,
  MockServiceStats,
  TestContainerOptions,
} from './types.mjs'
 
import { Container } from '../container/container.mjs'
import { InjectableScope, InjectableType } from '../enums/index.mjs'
import {
  BoundInjectionToken,
  InjectionToken,
} from '../token/injection-token.mjs'
import { globalRegistry, Registry } from '../token/registry.mjs'
import { getInjectableToken } from '../utils/get-injectable-token.mjs'
import { defaultInjectors } from '../utils/index.mjs'
 
type AnyToken =
  | InjectionToken<any, any>
  | BoundInjectionToken<any, any>
  | (new (...args: any[]) => any)
 
/**
 * TestContainer extends Container with testing utilities.
 *
 * Provides simple value/class binding for integration/e2e tests,
 * plus assertion helpers and dependency graph inspection.
 *
 * @example
 * ```ts
 * const container = new TestContainer()
 *
 * // Bind mock values
 * container.bind(DatabaseToken).toValue(mockDatabase)
 * container.bind(UserService).toClass(MockUserService)
 *
 * // Use container normally
 * const service = await container.get(MyService)
 *
 * // Assert on container state
 * container.expectResolved(MyService)
 * container.expectSingleton(MyService)
 * ```
 */
export class TestContainer extends Container {
  private readonly testRegistry: Registry
  private readonly methodCalls = new Map<string, MethodCallRecord[]>()
  private readonly lifecycleEvents = new Map<string, LifecycleRecord[]>()
  private readonly instanceCounts = new Map<string, number>()
  private readonly boundTokens = new Set<string>()
 
  /**
   * Creates a new TestContainer.
   *
   * @param options - Configuration options
   * @param options.parentRegistry - Parent registry. Defaults to globalRegistry.
   *   Pass `null` for a completely isolated container.
   * @param options.logger - Optional logger for debugging.
   *
   * @example
   * ```ts
   * // Uses globalRegistry as parent (default)
   * const container = new TestContainer()
   *
   * // Isolated container (no access to @Injectable classes)
   * const isolated = new TestContainer({ parentRegistry: null })
   *
   * // Custom parent registry
   * const custom = new TestContainer({ parentRegistry: myRegistry })
   * ```
   */
  constructor(options: TestContainerOptions = {}) {
    const { parentRegistry = globalRegistry, logger = null } = options
    const testRegistry = parentRegistry
      ? new Registry(parentRegistry)
      : new Registry()
    super(testRegistry, logger, defaultInjectors)
    this.testRegistry = testRegistry
  }
 
  // ============================================================================
  // BINDING API
  // ============================================================================
 
  /**
   * Creates a binding builder for the given token.
   *
   * @example
   * ```ts
   * container.bind(UserService).toValue(mockUserService)
   * container.bind(DatabaseToken).toClass(MockDatabase)
   * container.bind(ConfigToken).toFactory(() => ({ apiKey: 'test' }))
   * container.bind(BOUND_CONFIG_TOKEN).toValue(overrideValue)
   * ```
   */
  bind<T>(
    token:
      | InjectionToken<T, any>
      | BoundInjectionToken<T, any>
      | (new (...args: any[]) => T),
  ): BindingBuilder<T> {
    const realToken = this.resolveToken(token)
    const tokenId = realToken.id
 
    return {
      toValue: (value: T) => {
        this.boundTokens.add(tokenId)
        this.registerValueBinding(realToken, value)
      },
      toClass: <C extends new (...args: any[]) => T>(cls: C) => {
        this.boundTokens.add(tokenId)
        this.registerClassBinding(realToken, cls)
      },
      toFactory: (factory: () => T | Promise<T>) => {
        this.boundTokens.add(tokenId)
        this.registerFactoryBinding(realToken, factory)
      },
    }
  }
 
  /**
   * Clears all bindings and resets container state.
   */
  async clear(): Promise<void> {
    await this.dispose()
    this.methodCalls.clear()
    this.lifecycleEvents.clear()
    this.instanceCounts.clear()
    this.boundTokens.clear()
  }
 
  // ============================================================================
  // ASSERTION HELPERS
  // ============================================================================
 
  /**
   * Asserts that a service has been resolved at least once.
   */
  expectResolved(token: AnyToken): void {
    const realToken = this.resolveToken(token)
    const storage = this.getStorage()
    const names = storage.getAllNames()
    const found = names.some((name) => name.includes(realToken.id))
 
    if (!found) {
      throw new Error(
        `Expected ${realToken.toString()} to be resolved, but it was not`,
      )
    }
  }
 
  /**
   * Asserts that a service has NOT been resolved.
   */
  expectNotResolved(token: AnyToken): void {
    const realToken = this.resolveToken(token)
    const storage = this.getStorage()
    const names = storage.getAllNames()
    const found = names.some((name) => name.includes(realToken.id))
 
    if (found) {
      throw new Error(
        `Expected ${realToken.toString()} to NOT be resolved, but it was`,
      )
    }
  }
 
  /**
   * Asserts that a service is registered as singleton scope.
   */
  expectSingleton(token: AnyToken): void {
    const realToken = this.resolveToken(token)
    const registry = this.getRegistry()
 
    Iif (!registry.has(realToken)) {
      throw new Error(
        `Expected ${realToken.toString()} to be registered, but it was not`,
      )
    }
 
    const record = registry.get(realToken)
    Iif (record.scope !== InjectableScope.Singleton) {
      throw new Error(
        `Expected ${realToken.toString()} to be Singleton scope, but it was ${record.scope}`,
      )
    }
  }
 
  /**
   * Asserts that a service is registered as transient scope.
   */
  expectTransient(token: AnyToken): void {
    const realToken = this.resolveToken(token)
    const registry = this.getRegistry()
 
    Iif (!registry.has(realToken)) {
      throw new Error(
        `Expected ${realToken.toString()} to be registered, but it was not`,
      )
    }
 
    const record = registry.get(realToken)
    Iif (record.scope !== InjectableScope.Transient) {
      throw new Error(
        `Expected ${realToken.toString()} to be Transient scope, but it was ${record.scope}`,
      )
    }
  }
 
  /**
   * Asserts that a service is registered as request scope.
   */
  expectRequestScoped(token: AnyToken): void {
    const realToken = this.resolveToken(token)
    const registry = this.getRegistry()
 
    Iif (!registry.has(realToken)) {
      throw new Error(
        `Expected ${realToken.toString()} to be registered, but it was not`,
      )
    }
 
    const record = registry.get(realToken)
    Iif (record.scope !== InjectableScope.Request) {
      throw new Error(
        `Expected ${realToken.toString()} to be Request scope, but it was ${record.scope}`,
      )
    }
  }
 
  /**
   * Asserts that two service resolutions return the same instance.
   */
  async expectSameInstance(token: AnyToken): Promise<void> {
    const instance1 = await this.get(token as any)
    const instance2 = await this.get(token as any)
 
    Iif (instance1 !== instance2) {
      const realToken = this.resolveToken(token)
      throw new Error(
        `Expected ${realToken.toString()} to return same instance, but got different instances`,
      )
    }
  }
 
  /**
   * Asserts that two service resolutions return different instances.
   */
  async expectDifferentInstances(token: AnyToken): Promise<void> {
    const instance1 = await this.get(token as any)
    const instance2 = await this.get(token as any)
 
    Iif (instance1 === instance2) {
      const realToken = this.resolveToken(token)
      throw new Error(
        `Expected ${realToken.toString()} to return different instances, but got same instance`,
      )
    }
  }
 
  // ============================================================================
  // LIFECYCLE ASSERTIONS
  // ============================================================================
 
  /**
   * Asserts that a service's onServiceInit was called.
   */
  expectInitialized(token: AnyToken): void {
    const realToken = this.resolveToken(token)
    const events = this.lifecycleEvents.get(realToken.id) || []
    const initialized = events.some((e) => e.event === 'initialized')
 
    if (!initialized) {
      throw new Error(
        `Expected ${realToken.toString()} to be initialized, but onServiceInit was not called`,
      )
    }
  }
 
  /**
   * Asserts that a service's onServiceDestroy was called.
   */
  expectDestroyed(token: AnyToken): void {
    const realToken = this.resolveToken(token)
    const events = this.lifecycleEvents.get(realToken.id) || []
    const destroyed = events.some((e) => e.event === 'destroyed')
 
    if (!destroyed) {
      throw new Error(
        `Expected ${realToken.toString()} to be destroyed, but onServiceDestroy was not called`,
      )
    }
  }
 
  /**
   * Asserts that a service has NOT been destroyed.
   */
  expectNotDestroyed(token: AnyToken): void {
    const realToken = this.resolveToken(token)
    const events = this.lifecycleEvents.get(realToken.id) || []
    const destroyed = events.some((e) => e.event === 'destroyed')
 
    if (destroyed) {
      throw new Error(
        `Expected ${realToken.toString()} to NOT be destroyed, but onServiceDestroy was called`,
      )
    }
  }
 
  // ============================================================================
  // CALL TRACKING
  // ============================================================================
 
  /**
   * Records a method call for tracking.
   * Call this from your mock implementations.
   */
  recordMethodCall(
    token: AnyToken,
    method: string,
    args: unknown[],
    result?: unknown,
    error?: Error,
  ): void {
    const realToken = this.resolveToken(token)
    const calls = this.methodCalls.get(realToken.id) || []
    calls.push({
      method,
      args,
      timestamp: Date.now(),
      result,
      error,
    })
    this.methodCalls.set(realToken.id, calls)
  }
 
  /**
   * Records a lifecycle event for tracking.
   */
  recordLifecycleEvent(
    token: AnyToken,
    event: 'created' | 'initialized' | 'destroyed',
    instanceName: string,
  ): void {
    const realToken = this.resolveToken(token)
    const events = this.lifecycleEvents.get(realToken.id) || []
    events.push({
      event,
      timestamp: Date.now(),
      instanceName,
    })
    this.lifecycleEvents.set(realToken.id, events)
 
    Eif (event === 'created') {
      const count = this.instanceCounts.get(realToken.id) || 0
      this.instanceCounts.set(realToken.id, count + 1)
    }
  }
 
  /**
   * Asserts that a method was called on a service.
   */
  expectCalled(token: AnyToken, method: string): void {
    const realToken = this.resolveToken(token)
    const calls = this.methodCalls.get(realToken.id) || []
    const found = calls.some((c) => c.method === method)
 
    Iif (!found) {
      throw new Error(
        `Expected ${realToken.toString()}.${method}() to be called, but it was not`,
      )
    }
  }
 
  /**
   * Asserts that a method was called with specific arguments.
   */
  expectCalledWith(
    token: AnyToken,
    method: string,
    expectedArgs: unknown[],
  ): void {
    const realToken = this.resolveToken(token)
    const calls = this.methodCalls.get(realToken.id) || []
    const found = calls.some(
      (c) => c.method === method && this.argsMatch(c.args, expectedArgs),
    )
 
    Iif (!found) {
      throw new Error(
        `Expected ${realToken.toString()}.${method}() to be called with ${JSON.stringify(expectedArgs)}, but it was not`,
      )
    }
  }
 
  /**
   * Asserts that a method was called a specific number of times.
   */
  expectCallCount(token: AnyToken, method: string, count: number): void {
    const realToken = this.resolveToken(token)
    const calls = this.methodCalls.get(realToken.id) || []
    const actualCount = calls.filter((c) => c.method === method).length
 
    Iif (actualCount !== count) {
      throw new Error(
        `Expected ${realToken.toString()}.${method}() to be called ${count} times, but was called ${actualCount} times`,
      )
    }
  }
 
  /**
   * Gets all recorded method calls for a service.
   */
  getMethodCalls(token: AnyToken): MethodCallRecord[] {
    const realToken = this.resolveToken(token)
    return this.methodCalls.get(realToken.id) || []
  }
 
  /**
   * Gets statistics about a mocked service.
   */
  getServiceStats(token: AnyToken): MockServiceStats {
    const realToken = this.resolveToken(token)
    return {
      instanceCount: this.instanceCounts.get(realToken.id) || 0,
      methodCalls: this.methodCalls.get(realToken.id) || [],
      lifecycleEvents: this.lifecycleEvents.get(realToken.id) || [],
    }
  }
 
  /**
   * Clears all recorded method calls.
   */
  clearMethodCalls(): void {
    this.methodCalls.clear()
  }
 
  // ============================================================================
  // DEPENDENCY GRAPH
  // ============================================================================
 
  /**
   * Gets the dependency graph for snapshot testing.
   * Returns a serializable structure that can be used with vitest snapshots.
   */
  getDependencyGraph(): DependencyGraph {
    const storage = this.getStorage()
    const nodes: Record<string, DependencyNode> = {}
    const rootTokens: string[] = []
 
    storage.forEach((name, holder) => {
      const tokenMatch = name.match(/^([^:]+)/)
      const tokenId = tokenMatch ? tokenMatch[1] : name
 
      nodes[name] = {
        token: tokenId,
        instanceName: name,
        scope: holder.scope,
        dependencies: Array.from(holder.deps),
        dependents: storage.findDependents(name),
      }
 
      // Root tokens have no dependents
      Eif (storage.findDependents(name).length === 0) {
        rootTokens.push(name)
      }
    })
 
    return { nodes, rootTokens }
  }
 
  /**
   * Gets a simplified dependency graph showing only token relationships.
   * Useful for cleaner snapshot comparisons.
   */
  getSimplifiedDependencyGraph(): Record<string, string[]> {
    const storage = this.getStorage()
    const graph: Record<string, string[]> = {}
 
    storage.forEach((name, holder) => {
      const tokenMatch = name.match(/^([^:]+)/)
      const tokenId = tokenMatch ? tokenMatch[1] : name
 
      Eif (!graph[tokenId]) {
        graph[tokenId] = []
      }
 
      for (const dep of holder.deps) {
        const depTokenMatch = dep.match(/^([^:]+)/)
        const depTokenId = depTokenMatch ? depTokenMatch[1] : dep
        if (!graph[tokenId].includes(depTokenId)) {
          graph[tokenId].push(depTokenId)
        }
      }
    })
 
    // Sort for consistent snapshots
    for (const key of Object.keys(graph)) {
      graph[key].sort()
    }
 
    return graph
  }
 
  // ============================================================================
  // INTERNAL HELPERS
  // ============================================================================
 
  private resolveToken(token: AnyToken): InjectionToken<any, any> {
    if (typeof token === 'function') {
      return getInjectableToken(token)
    }
    Iif (token instanceof BoundInjectionToken) {
      return token.token
    }
    return token
  }
 
  private registerValueBinding<T>(
    token: InjectionToken<T, any>,
    value: T,
  ): void {
    // Create a simple class that returns the value
    const ValueHolder = class {
      create(): T {
        return value
      }
    }
 
    this.testRegistry.set(
      token,
      InjectableScope.Singleton,
      ValueHolder,
      InjectableType.Factory,
      1000, // Higher priority for test overrides
    )
 
    // Store the instance directly
    const nameResolver = this.getNameResolver()
    const instanceName = nameResolver.generateInstanceName(
      token,
      undefined,
      undefined,
      InjectableScope.Singleton,
    )
    this.getStorage().storeInstance(instanceName, value)
    this.recordLifecycleEvent(token, 'created', instanceName)
  }
 
  private registerClassBinding<T>(
    token: InjectionToken<T, any>,
    cls: new (...args: any[]) => T,
  ): void {
    this.testRegistry.set(
      token,
      InjectableScope.Singleton,
      cls,
      InjectableType.Class,
      1000, // Higher priority for test overrides
    )
  }
 
  private registerFactoryBinding<T>(
    token: InjectionToken<T, any>,
    factory: () => T | Promise<T>,
  ): void {
    // Create a factory class wrapper
    const FactoryWrapper = class {
      static factory = factory
      async create(): Promise<T> {
        return await factory()
      }
    }
 
    this.testRegistry.set(
      token,
      InjectableScope.Singleton,
      FactoryWrapper,
      InjectableType.Factory,
      1000, // Higher priority for test overrides
    )
  }
 
  private argsMatch(actual: unknown[], expected: unknown[]): boolean {
    Iif (actual.length !== expected.length) {
      return false
    }
    return actual.every((arg, index) => {
      const exp = expected[index]
      Iif (typeof exp === 'object' && exp !== null) {
        return JSON.stringify(arg) === JSON.stringify(exp)
      }
      return arg === exp
    })
  }
}