All files / src/testing unit-test-container.mts

76.84% Statements 146/190
71.92% Branches 82/114
79.59% Functions 39/49
77.9% Lines 141/181

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 601 602                                                                16x   35x   35x 11x 11x 11x           11x 11x   11x 1x   1x 1x 1x 1x                   10x 10x 10x 10x                   24x                 6x       7x 6x   1x     1x                                                                         29x 29x 29x 29x 29x       29x 29x 29x 29x     29x 19x                 1x 1x               1x 1x               25x 25x 25x       25x     25x 9x 3x             6x 9x 6x     6x     16x     16x 25x 16x                   1x 1x 1x 1x 1x                     2x 2x 2x 4x   2x                     2x 2x 2x 2x   2x                     2x   2x                       1x   1x                                     3x 3x 3x         3x   3x 3x 3x                                                                                                                 4x 4x 4x   4x                     1x 1x 1x   1x                             2x 2x 2x 2x     2x                               1x 1x 3x   1x                     1x 1x             1x 1x                                   1x             1x               64x 47x 47x           17x 8x   9x       19x 19x     19x 19x 4x     19x 2x 17x 2x 15x 2x     13x 12x             1x   1x                 3x   2x       3x               3x 3x           3x 3x             2x                         2x 2x   2x       2x                   2x     2x 2x 2x     2x        
import type {
  LifecycleRecord,
  MethodCallRecord,
  MockServiceStats,
  ProviderConfig,
  UnitTestContainerOptions,
} from './types.mjs'
 
import { Container } from '../container/container.mjs'
import { InjectableScope, InjectableType } from '../enums/index.mjs'
import { DIError } from '../errors/index.mjs'
import {
  BoundInjectionToken,
  InjectionToken,
} from '../token/injection-token.mjs'
import { 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)
 
/**
 * Creates a tracking proxy that records method calls.
 */
function createTrackingProxy<T extends object>(
  target: T,
  tokenId: string,
  methodCalls: Map<string, MethodCallRecord[]>,
): T {
  return new Proxy(target, {
    get(obj, prop) {
      const value = Reflect.get(obj, prop)
 
      if (typeof value === 'function' && typeof prop === 'string') {
        return function (this: unknown, ...args: unknown[]) {
          const calls = methodCalls.get(tokenId) || []
          const record: MethodCallRecord = {
            method: prop,
            args,
            timestamp: Date.now(),
          }
 
          try {
            const result = value.apply(this === undefined ? obj : this, args)
 
            if (result instanceof Promise) {
              return result
                .then((res) => {
                  record.result = res
                  calls.push(record)
                  methodCalls.set(tokenId, calls)
                  return res
                })
                .catch((err) => {
                  record.error = err
                  calls.push(record)
                  methodCalls.set(tokenId, calls)
                  throw err
                })
            }
 
            record.result = result
            calls.push(record)
            methodCalls.set(tokenId, calls)
            return result
          } catch (err) {
            record.error = err as Error
            calls.push(record)
            methodCalls.set(tokenId, calls)
            throw err
          }
        }
      }
 
      return value
    },
  })
}
 
/**
 * Creates an auto-mock proxy that throws on method access.
 */
function createAutoMockProxy(tokenId: string): object {
  return new Proxy(
    {},
    {
      get(_, prop) {
        if (prop === 'then' || prop === 'catch' || prop === 'finally') {
          return undefined
        }
        Iif (typeof prop === 'symbol') {
          return undefined
        }
        throw new Error(
          `[UnitTestContainer] Attempted to access '${prop}' on auto-mocked service '${tokenId}'. ` +
            `This service was not provided in the providers list. ` +
            `Add it to providers or use allowUnregistered: false to catch this earlier.`,
        )
      },
    },
  )
}
 
/**
 * UnitTestContainer for isolated unit testing.
 *
 * Only services explicitly listed in `providers` can be resolved.
 * All method calls are automatically tracked via proxies.
 * Unregistered dependencies throw by default, or can be auto-mocked.
 *
 * @example
 * ```ts
 * const container = new UnitTestContainer({
 *   providers: [
 *     { token: UserService, useClass: MockUserService },
 *     { token: ConfigToken, useValue: { apiUrl: 'test' } },
 *   ],
 * })
 *
 * const service = await container.get(UserService)
 *
 * // All method calls are automatically tracked
 * await service.findUser('123')
 *
 * container.expectCalled(UserService, 'findUser')
 * container.expectCalledWith(UserService, 'findUser', ['123'])
 * ```
 */
export class UnitTestContainer 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 registeredTokenIds = new Set<string>()
  private readonly autoMockedTokenIds = new Set<string>()
  private allowUnregistered: boolean
 
  constructor(options: UnitTestContainerOptions) {
    const testRegistry = new Registry()
    super(testRegistry, options.logger ?? null, defaultInjectors)
    this.testRegistry = testRegistry
    this.allowUnregistered = options.allowUnregistered ?? false
 
    // Register all providers
    for (const provider of options.providers) {
      this.registerProvider(provider)
    }
  }
 
  /**
   * Enables auto-mocking for unregistered dependencies.
   * Call this to switch from strict mode to auto-mock mode.
   */
  enableAutoMocking(): this {
    this.allowUnregistered = true
    return this
  }
 
  /**
   * Disables auto-mocking (strict mode).
   * Unregistered dependencies will throw.
   */
  disableAutoMocking(): this {
    this.allowUnregistered = false
    return this
  }
 
  /**
   * Override get to wrap instances in tracking proxies.
   */
  override async get(token: any, args?: unknown): Promise<any> {
    // Check if token is a BoundInjectionToken and if it's registered
    const isBoundToken = token instanceof BoundInjectionToken
    const tokenId = isBoundToken ? token.id : undefined
    const realToken = this.resolveToken(token)
 
    // Check if this is a registered provider (check both bound token ID and real token ID)
    const isRegistered =
      (tokenId && this.registeredTokenIds.has(tokenId)) ||
      this.registeredTokenIds.has(realToken.id)
 
    if (!isRegistered) {
      if (!this.allowUnregistered) {
        throw DIError.factoryNotFound(
          `${realToken.toString()} is not in the providers list. ` +
            `Add it to providers or enable allowUnregistered.`,
        )
      }
 
      // Auto-mock unregistered dependency
      const idToCheck = tokenId || realToken.id
      if (!this.autoMockedTokenIds.has(idToCheck)) {
        this.autoMockedTokenIds.add(idToCheck)
      }
 
      return createAutoMockProxy(idToCheck)
    }
 
    const instance = await super.get(token, args)
 
    // Wrap in tracking proxy if it's an object
    const trackingId = tokenId || realToken.id
    if (instance && typeof instance === 'object') {
      return createTrackingProxy(instance, trackingId, this.methodCalls)
    }
 
    return instance
  }
 
  /**
   * Clears all state and disposes the container.
   */
  async clear(): Promise<void> {
    await this.dispose()
    this.methodCalls.clear()
    this.lifecycleEvents.clear()
    this.instanceCounts.clear()
    this.autoMockedTokenIds.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))
 
    Iif (!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))
 
    Iif (found) {
      throw new Error(
        `Expected ${realToken.toString()} to NOT be resolved, but it was`,
      )
    }
  }
 
  /**
   * Asserts that a service was auto-mocked (not in providers list).
   */
  expectAutoMocked(token: AnyToken): void {
    const realToken = this.resolveToken(token)
 
    Iif (!this.autoMockedTokenIds.has(realToken.id)) {
      throw new Error(
        `Expected ${realToken.toString()} to be auto-mocked, but it was not. ` +
          `Either it's in the providers list or hasn't been resolved.`,
      )
    }
  }
 
  /**
   * Asserts that a service was NOT auto-mocked (is in providers list).
   */
  expectNotAutoMocked(token: AnyToken): void {
    const realToken = this.resolveToken(token)
 
    Iif (this.autoMockedTokenIds.has(realToken.id)) {
      throw new Error(
        `Expected ${realToken.toString()} to NOT be auto-mocked, but it was.`,
      )
    }
  }
 
  // ============================================================================
  // LIFECYCLE ASSERTIONS
  // ============================================================================
 
  /**
   * 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 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 (AUTO-TRACKED VIA PROXY)
  // ============================================================================
 
  /**
   * 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 NOT called on a service.
   */
  expectNotCalled(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 NOT be called, but it was`,
      )
    }
  }
 
  /**
   * 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) {
      const methodCalls = calls.filter((c) => c.method === method)
      const actualArgs = methodCalls
        .map((c) => JSON.stringify(c.args))
        .join(', ')
      throw new Error(
        `Expected ${realToken.toString()}.${method}() to be called with ${JSON.stringify(expectedArgs)}. ` +
          `Actual calls: [${actualArgs}]`,
      )
    }
  }
 
  /**
   * 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 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()
  }
 
  /**
   * Gets list of all registered provider token IDs.
   */
  getRegisteredTokenIds(): ReadonlySet<string> {
    return this.registeredTokenIds
  }
 
  /**
   * Gets list of all auto-mocked token IDs.
   */
  getAutoMockedTokenIds(): ReadonlySet<string> {
    return this.autoMockedTokenIds
  }
 
  // ============================================================================
  // INTERNAL HELPERS
  // ============================================================================
 
  private resolveToken(token: AnyToken): InjectionToken<any, any> {
    if (typeof token === 'function') {
      try {
        return getInjectableToken(token)
      } catch {
        // Class doesn't have @Injectable, create a token for it
        return InjectionToken.create(token)
      }
    }
    if (token instanceof BoundInjectionToken) {
      return token.token
    }
    return token
  }
 
  private registerProvider<T>(provider: ProviderConfig<T>): void {
    const providerToken = provider.token as AnyToken
    const realToken = this.resolveToken(providerToken)
 
    // Track both the real token ID and the bound token ID if it's a bound token
    this.registeredTokenIds.add(realToken.id)
    if (providerToken instanceof BoundInjectionToken) {
      this.registeredTokenIds.add(providerToken.id)
    }
 
    if (provider.useValue !== undefined) {
      this.registerValueBinding(realToken, provider.useValue)
    } else if (provider.useClass) {
      this.registerClassBinding(realToken, provider.useClass)
    } else if (provider.useFactory) {
      this.registerFactoryBinding(realToken, provider.useFactory)
    } else {
      // Just the token - register as itself
      if (typeof provider.token === 'function') {
        this.testRegistry.set(
          realToken,
          InjectableScope.Singleton,
          provider.token,
          InjectableType.Class,
          1000, // Higher priority for test overrides
        )
      E} else if (providerToken instanceof BoundInjectionToken) {
        // If it's a bound token without override, register the bound value
        this.registerValueBinding(realToken, providerToken.value)
      }
    }
  }
 
  private registerValueBinding<T>(
    token: InjectionToken<T, any>,
    value: T,
  ): void {
    const ValueHolder = class {
      create(): T {
        return value
      }
    }
 
    this.testRegistry.set(
      token,
      InjectableScope.Singleton,
      ValueHolder,
      InjectableType.Factory,
      1000, // Higher priority for test overrides
    )
 
    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 {
    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
    })
  }
}