From 863ce94a8ea0f2bca8d450c260502c7e413d265b Mon Sep 17 00:00:00 2001 From: omermorad Date: Sat, 28 Nov 2026 23:10:19 +0200 Subject: [PATCH 1/8] test(unit): cover generated mocks and constructor-time final values --- e2e/jest/nestjs/mock-and-final.e2e.test.ts | 75 +++++++++++++++++++ .../inversify/mock-and-final.e2e.test.ts | 58 ++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 e2e/jest/nestjs/mock-and-final.e2e.test.ts create mode 100644 e2e/vitest/inversify/mock-and-final.e2e.test.ts diff --git a/e2e/jest/nestjs/mock-and-final.e2e.test.ts b/e2e/jest/nestjs/mock-and-final.e2e.test.ts new file mode 100644 index 00000000..eb89457e --- /dev/null +++ b/e2e/jest/nestjs/mock-and-final.e2e.test.ts @@ -0,0 +1,75 @@ +import 'reflect-metadata'; +import { expect, it, jest } from '@jest/globals'; +import { Injectable } from '@nestjs/common'; +import { TestBed } from '@suites/unit'; + +@Injectable() +class PaymentGateway { + constructor() { + throw new Error('The real payment gateway was constructed'); + } + + charge(): string { + return 'live receipt'; + } +} + +@Injectable() +class Checkout { + constructor(readonly payments: PaymentGateway) {} + + pay(): string { + return this.payments.charge(); + } +} + +it('configures a generated mock before the first checkout call', async () => { + const configured = TestBed.sociable(Checkout).mock(PaymentGateway); + // @ts-expect-error A mock declaration returns the configured builder. + expect(configured.impl).toBeUndefined(); + const { unit, unitRef } = await configured.compile(); + const payments = unitRef.get(PaymentGateway); + payments.charge.mockReturnValue('receipt-1'); + + expect(unit.payments).toBe(payments); + expect(unit.pay()).toBe('receipt-1'); + expect(payments.charge).toHaveBeenCalledTimes(1); +}); + +@Injectable() +class Purchase { + readonly receipt: string; + + constructor(readonly payments: PaymentGateway) { + this.receipt = payments.charge(); + } +} + +@Injectable() +class PurchaseOrder { + constructor(readonly purchase: Purchase) {} +} + +it('injects an exact final value before constructing a nested collaborator', async () => { + const payments = { charge: jest.fn(() => 'prepaid') } satisfies PaymentGateway; + const { unit, unitRef } = await TestBed.sociable(PurchaseOrder) + .final(PaymentGateway, payments) + .compile(); + + expect(unit.purchase).toBeInstanceOf(Purchase); + expect(unit.purchase.payments).toBe(payments); + expect(unit.purchase.receipt).toBe('prepaid'); + expect(payments.charge).toHaveBeenCalledTimes(1); + expect(() => unitRef.get(PaymentGateway)).toThrow(/ER040/); +}); + +it('requires a token and compatible value for a final declaration', () => { + const defineInvalidOverrides = () => { + const builder = TestBed.solitary(Checkout); + // @ts-expect-error The value alone does not identify the dependency. + builder.mock(PaymentGateway).final({ charge: () => 'paid' }); + // @ts-expect-error The supplied method must return a string. + builder.final(PaymentGateway, { charge: () => 12 }); + }; + expect(typeof defineInvalidOverrides).toBe('function'); +}); diff --git a/e2e/vitest/inversify/mock-and-final.e2e.test.ts b/e2e/vitest/inversify/mock-and-final.e2e.test.ts new file mode 100644 index 00000000..022fbb6e --- /dev/null +++ b/e2e/vitest/inversify/mock-and-final.e2e.test.ts @@ -0,0 +1,58 @@ +import 'reflect-metadata'; +import { expect, it, vi } from 'vitest'; +import { inject, injectable, named } from 'inversify'; +import { TestBed } from '@suites/unit'; + +@injectable() +class Exchange { + currency(): string { + return 'live'; + } +} + +@injectable() +class Price { + readonly currencyAtConstruction: string; + + constructor( + @inject(Exchange) @named('billing') readonly billing: Exchange, + @inject(Exchange) @named('display') readonly display: Exchange + ) { + this.currencyAtConstruction = billing.currency(); + } +} + +@injectable() +class Catalog { + constructor(@inject(Price) readonly price: Price) {} +} + +it('selects a final and a generated mock by qualifier inside a real collaborator', async () => { + const billing = { currency: vi.fn(() => 'USD') } satisfies Exchange; + const { unit, unitRef } = await TestBed.sociable(Catalog) + .expose(Price) + .final(Exchange, billing, { named: 'billing' }) + .mock(Exchange, { named: 'display' }) + .compile(); + const display = unitRef.get(Exchange, { named: 'display' }); + display.currency.mockReturnValue('EUR'); + + expect(unit.price).toBeInstanceOf(Price); + expect(unit.price.billing).toBe(billing); + expect(unit.price.currencyAtConstruction).toBe('USD'); + expect(unit.price.display).toBe(display); + expect(unit.price.display.currency()).toBe('EUR'); + expect(() => unitRef.get(Exchange, { named: 'billing' })).toThrow(/ER040/); +}); + +it('can supply a final before a solitary root constructor runs', async () => { + const billing = { currency: () => 'CAD' }; + const { unit, unitRef } = await TestBed.solitary(Price) + .final(Exchange, billing, { named: 'billing' }) + .mock(Exchange, { named: 'display' }) + .compile(); + + expect(unit.billing).toBe(billing); + expect(unit.currencyAtConstruction).toBe('CAD'); + expect(unit.display).toBe(unitRef.get(Exchange, { named: 'display' })); +}); From 634715a39049740c4792eb460449d78523491ad8 Mon Sep 17 00:00:00 2001 From: omermorad Date: Sat, 28 Nov 2026 23:12:57 +0200 Subject: [PATCH 2/8] test(unit): migrate consumers to generated mocks and ready final values --- .../injection-js/abstract-tokens.e2e.test.ts | 18 +++------- .../jest/injection-js/composition.e2e.test.ts | 6 ++-- .../injection-js/ctor-injection.e2e.test.ts | 18 ++++------ .../jest/nestjs/abstract-tokens.e2e.test.ts | 18 +++------- e2e/esm/jest/nestjs/composition.e2e.test.ts | 6 ++-- e2e/esm/jest/nestjs/getters.e2e.test.ts | 17 ++++------ .../suites-jest-ctor-injection.e2e.test.ts | 26 ++++++--------- e2e/esm/jest/nestjs/type-safety.e2e.test.ts | 3 +- .../injection-js/abstract-tokens.e2e.test.ts | 18 +++------- .../injection-js/composition.e2e.test.ts | 6 ++-- .../injection-js/ctor-injection.e2e.test.ts | 18 ++++------ .../vitest/nestjs/abstract-tokens.e2e.test.ts | 18 +++------- e2e/esm/vitest/nestjs/composition.e2e.test.ts | 6 ++-- e2e/esm/vitest/nestjs/getters.e2e.test.ts | 17 ++++------ .../suites-vitest-ctor-injection.e2e.test.ts | 30 +++++++---------- e2e/esm/vitest/nestjs/type-safety.e2e.test.ts | 3 +- .../injection-js/abstract-tokens.e2e.test.ts | 18 +++------- e2e/jest/injection-js/binding.e2e.test.ts | 7 ++-- e2e/jest/injection-js/composition.e2e.test.ts | 6 ++-- .../injection-js/ctor-injection.e2e.test.ts | 20 +++++------ .../forbidden-boundaries.guard.test.ts | 3 +- .../inversify/abstract-tokens.e2e.test.ts | 24 +++++--------- e2e/jest/inversify/binding.e2e.test.ts | 8 ++--- e2e/jest/inversify/composition.e2e.test.ts | 6 ++-- e2e/jest/inversify/ctor-injection.e2e.test.ts | 33 +++++++------------ .../forbidden-boundaries.guard.test.ts | 3 +- .../qualified-dependencies.e2e.test.ts | 8 ++--- .../inversify/strict-declarations.e2e.test.ts | 28 +++++----------- e2e/jest/inversify/type-safety.e2e.test.ts | 9 ++--- e2e/jest/nestjs/abstract-tokens.e2e.test.ts | 18 +++------- e2e/jest/nestjs/binding.e2e.test.ts | 14 +++----- e2e/jest/nestjs/composition.e2e.test.ts | 6 ++-- .../nestjs/forbidden-boundaries.guard.test.ts | 8 +++-- e2e/jest/nestjs/getters.e2e.test.ts | 17 ++++------ .../suites-jest-ctor-injection.e2e.test.ts | 26 ++++++--------- .../suites-jest-prop-injection.e2e.test.ts | 18 ++++------ ...est-sociable-empty-constructor.e2e.test.ts | 1 - .../nestjs/suites-jest-sociable.e2e.test.ts | 8 ++--- e2e/jest/nestjs/type-safety.e2e.test.ts | 3 +- .../injection-js/abstract-tokens.e2e.test.ts | 18 +++------- .../injection-js/composition.e2e.test.ts | 6 ++-- .../injection-js/ctor-injection.e2e.test.ts | 18 ++++------ .../forbidden-boundaries.guard.test.ts | 3 +- .../inversify/abstract-tokens.e2e.test.ts | 24 +++++--------- e2e/vitest/inversify/binding.e2e.test.ts | 8 ++--- e2e/vitest/inversify/composition.e2e.test.ts | 6 ++-- .../inversify/ctor-injection.e2e.test.ts | 33 +++++++------------ .../forbidden-boundaries.guard.test.ts | 3 +- .../qualified-dependencies.e2e.test.ts | 8 ++--- e2e/vitest/inversify/type-safety.e2e.test.ts | 9 ++--- e2e/vitest/nestjs/abstract-tokens.e2e.test.ts | 18 +++------- e2e/vitest/nestjs/composition.e2e.test.ts | 6 ++-- .../nestjs/forbidden-boundaries.guard.test.ts | 3 +- e2e/vitest/nestjs/getters.e2e.test.ts | 17 ++++------ .../suites-vitest-ctor-injection.e2e.test.ts | 30 +++++++---------- e2e/vitest/nestjs/type-safety.e2e.test.ts | 3 +- 56 files changed, 255 insertions(+), 478 deletions(-) diff --git a/e2e/esm/jest/injection-js/abstract-tokens.e2e.test.ts b/e2e/esm/jest/injection-js/abstract-tokens.e2e.test.ts index 42677623..370973e2 100644 --- a/e2e/esm/jest/injection-js/abstract-tokens.e2e.test.ts +++ b/e2e/esm/jest/injection-js/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/esm/jest/injection-js/composition.e2e.test.ts b/e2e/esm/jest/injection-js/composition.e2e.test.ts index ef9eb6af..ed81753c 100644 --- a/e2e/esm/jest/injection-js/composition.e2e.test.ts +++ b/e2e/esm/jest/injection-js/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/esm/jest/injection-js/ctor-injection.e2e.test.ts b/e2e/esm/jest/injection-js/ctor-injection.e2e.test.ts index 2f56ca16..ac7456e7 100644 --- a/e2e/esm/jest/injection-js/ctor-injection.e2e.test.ts +++ b/e2e/esm/jest/injection-js/ctor-injection.e2e.test.ts @@ -43,10 +43,8 @@ class Service { describe('published InjectionJS adapter', () => { it('distinguishes finalized and mocked tokens with identical descriptions', async () => { const { unit, unitRef } = await TestBed.solitary(Service) - .mock(TOKEN) - .final({ find: () => 'final' }) - .mock(CONFIG) - .final('test') + .final(TOKEN, { find: () => 'final' }) + .final(CONFIG, 'test') .compile(); expect(unit.token.find()).toBe('final'); expect(unit.other).toBe(unitRef.get(OTHER)); @@ -59,8 +57,7 @@ describe('published InjectionJS adapter', () => { constructor(@Optional() @Inject(TOKEN) readonly repository: Repository | null) {} } const { unit } = await TestBed.solitary(OptionalService) - .mock(TOKEN) - .final(null) + .final(TOKEN, null) .compile(); expect(unit.repository).toBeNull(); }); @@ -68,10 +65,9 @@ describe('published InjectionJS adapter', () => { it('mocks class, string, symbol and InjectionToken dependencies', async () => { const { unit, unitRef } = await TestBed.solitary(Service) .mock(TOKEN) - .impl((stub) => ({ find: stub().mockReturnValue('mock') })) - .mock(CONFIG) - .final('test') + .final(CONFIG, 'test') .compile(); + unitRef.get(TOKEN).find.mockReturnValue('mock'); const repository: Mocked = unitRef.get(Repository); repository.find.mockReturnValue('class mock'); expect(unit.repository.find()).toBe('class mock'); @@ -137,12 +133,12 @@ describe('published InjectionJS adapter', () => { // This function is checked by tsc without executing the intentionally invalid calls. function checkPublicTypes() { const builder = TestBed.solitary(Service); - builder.mock(TOKEN).impl((stub) => ({ find: stub().mockReturnValue('ok') })); + builder.mock(TOKEN); // @ts-expect-error arbitrary object tokens are not registered builder.mock({}); // @ts-expect-error InjectionJS has no identifier metadata builder.mock(TOKEN, { tag: 'production' }); // @ts-expect-error a string token cannot be finalized with a number - builder.mock(CONFIG).final(42); + builder.final(CONFIG, 42); } void checkPublicTypes; diff --git a/e2e/esm/jest/nestjs/abstract-tokens.e2e.test.ts b/e2e/esm/jest/nestjs/abstract-tokens.e2e.test.ts index a510b94e..a5063ee5 100644 --- a/e2e/esm/jest/nestjs/abstract-tokens.e2e.test.ts +++ b/e2e/esm/jest/nestjs/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/esm/jest/nestjs/composition.e2e.test.ts b/e2e/esm/jest/nestjs/composition.e2e.test.ts index b9c0712d..36b3a81f 100644 --- a/e2e/esm/jest/nestjs/composition.e2e.test.ts +++ b/e2e/esm/jest/nestjs/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/esm/jest/nestjs/getters.e2e.test.ts b/e2e/esm/jest/nestjs/getters.e2e.test.ts index d6f78f06..f36b9293 100644 --- a/e2e/esm/jest/nestjs/getters.e2e.test.ts +++ b/e2e/esm/jest/nestjs/getters.e2e.test.ts @@ -23,20 +23,17 @@ class Application { describe('Supplied getter implementations', () => { it('configures a readonly getter through TestBed without assignment', async () => { let reads = 0; - const { unit, unitRef } = await TestBed.solitary(Application) - .mock(ConfigService) - .impl(() => ({ - get isCli() { - reads += 1; - return false; - }, - })) - .compile(); + const config = mock({ + get isCli() { + reads += 1; + return false; + }, + }); + const { unit } = await TestBed.solitary(Application).final(ConfigService, config).compile(); expect(reads).toBe(0); expect(unit.isCli()).toBe(false); expect(reads).toBe(1); - const config = unitRef.get(ConfigService); jest.spyOn(config, 'isCli', 'get').mockReturnValue(true); expect(unit.isCli()).toBe(true); }); diff --git a/e2e/esm/jest/nestjs/suites-jest-ctor-injection.e2e.test.ts b/e2e/esm/jest/nestjs/suites-jest-ctor-injection.e2e.test.ts index 62cc71ae..bc8f64e5 100644 --- a/e2e/esm/jest/nestjs/suites-jest-ctor-injection.e2e.test.ts +++ b/e2e/esm/jest/nestjs/suites-jest-ctor-injection.e2e.test.ts @@ -1,3 +1,4 @@ +import { mock } from '@suites/doubles.jest'; import type { UnitReference, Mocked } from '@suites/unit'; import { TestBed } from '@suites/unit'; import type { Logger, TestClassFive } from './e2e-assets.js'; @@ -13,27 +14,21 @@ import { describe('Suites Jest / NestJS E2E Test Ctor', () => { let unit: NestJSTestClass; let unitRef: UnitReference; + const testClassOne = mock(); beforeAll(async () => { + testClassOne.foo.mockResolvedValue('foo-from-test'); + testClassOne.bar.mockReturnValue('bar'); const { unitRef: ref, unit: underTest } = await TestBed.solitary( NestJSTestClass ) - .mock(TestClassOne) - .impl((stubFn) => ({ - foo: stubFn().mockResolvedValue('foo-from-test'), - bar(): string { - return 'bar'; - }, - })) - .mock('CONSTANT_VALUE') - .final('arbitrary-string') - .mock('UNDEFINED') - .final({ method: () => 456 }) + .final(TestClassOne, testClassOne) + .final('CONSTANT_VALUE', 'arbitrary-string') + .final('UNDEFINED', { method: () => 456 }) .mock('LOGGER') - .impl((stubFn) => ({ log: stubFn().mockReturnValue('baz-from-test') })) - .mock(SymbolToken) - .final({ doSomething: () => 'mocked' }) + .final(SymbolToken, { doSomething: () => 'mocked' }) .compile(); + ref.get('LOGGER').log.mockReturnValue('baz-from-test'); unitRef = ref; unit = underTest; @@ -46,7 +41,7 @@ describe('Suites Jest / NestJS E2E Test Ctor', () => { test('then successfully resolve the dependencies of the tested classes', () => { expect(() => unitRef.get<{ log: () => void }>('LOGGER')).toBeDefined(); - expect(() => unitRef.get(TestClassOne)).toBeDefined(); + expect(() => unitRef.get(TestClassOne)).toThrow(/faked dependency/); }); test('call the unit instance method', async () => { @@ -59,7 +54,6 @@ describe('Suites Jest / NestJS E2E Test Ctor', () => { }); test('then mock the implementation of the dependencies', async () => { - const testClassOne: Mocked = unitRef.get(TestClassOne); const logger = unitRef.get('LOGGER'); // The original 'foo' method in TestClassOne return value should be changed diff --git a/e2e/esm/jest/nestjs/type-safety.e2e.test.ts b/e2e/esm/jest/nestjs/type-safety.e2e.test.ts index cf27a15c..87cb4191 100644 --- a/e2e/esm/jest/nestjs/type-safety.e2e.test.ts +++ b/e2e/esm/jest/nestjs/type-safety.e2e.test.ts @@ -4,8 +4,7 @@ import { NestJSTestClass } from './e2e-assets.js'; describe('NestJS DI Adapter Type Safety', () => { it('allows mocking without metadata', async () => { const { unitRef } = await TestBed.solitary(NestJSTestClass) - .mock('CONSTANT_VALUE') - .final('test-value') + .final('CONSTANT_VALUE', 'test-value') .compile(); expect(unitRef).toBeDefined(); diff --git a/e2e/esm/vitest/injection-js/abstract-tokens.e2e.test.ts b/e2e/esm/vitest/injection-js/abstract-tokens.e2e.test.ts index 7310522b..67a811f2 100644 --- a/e2e/esm/vitest/injection-js/abstract-tokens.e2e.test.ts +++ b/e2e/esm/vitest/injection-js/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/esm/vitest/injection-js/composition.e2e.test.ts b/e2e/esm/vitest/injection-js/composition.e2e.test.ts index cfe3dbd6..d092506e 100644 --- a/e2e/esm/vitest/injection-js/composition.e2e.test.ts +++ b/e2e/esm/vitest/injection-js/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/esm/vitest/injection-js/ctor-injection.e2e.test.ts b/e2e/esm/vitest/injection-js/ctor-injection.e2e.test.ts index a9248658..b916c14e 100644 --- a/e2e/esm/vitest/injection-js/ctor-injection.e2e.test.ts +++ b/e2e/esm/vitest/injection-js/ctor-injection.e2e.test.ts @@ -43,10 +43,8 @@ class Service { describe('published InjectionJS adapter', () => { it('distinguishes finalized and mocked tokens with identical descriptions', async () => { const { unit, unitRef } = await TestBed.solitary(Service) - .mock(TOKEN) - .final({ find: () => 'final' }) - .mock(CONFIG) - .final('test') + .final(TOKEN, { find: () => 'final' }) + .final(CONFIG, 'test') .compile(); expect(unit.token.find()).toBe('final'); expect(unit.other).toBe(unitRef.get(OTHER)); @@ -59,8 +57,7 @@ describe('published InjectionJS adapter', () => { constructor(@Optional() @Inject(TOKEN) readonly repository: Repository | null) {} } const { unit } = await TestBed.solitary(OptionalService) - .mock(TOKEN) - .final(null) + .final(TOKEN, null) .compile(); expect(unit.repository).toBeNull(); }); @@ -68,10 +65,9 @@ describe('published InjectionJS adapter', () => { it('mocks class, string, symbol and InjectionToken dependencies', async () => { const { unit, unitRef } = await TestBed.solitary(Service) .mock(TOKEN) - .impl((stub) => ({ find: stub().mockReturnValue('mock') })) - .mock(CONFIG) - .final('test') + .final(CONFIG, 'test') .compile(); + unitRef.get(TOKEN).find.mockReturnValue('mock'); const repository: Mocked = unitRef.get(Repository); repository.find.mockReturnValue('class mock'); expect(unit.repository.find()).toBe('class mock'); @@ -137,12 +133,12 @@ describe('published InjectionJS adapter', () => { // This function is checked by tsc without executing the intentionally invalid calls. function checkPublicTypes() { const builder = TestBed.solitary(Service); - builder.mock(TOKEN).impl((stub) => ({ find: stub().mockReturnValue('ok') })); + builder.mock(TOKEN); // @ts-expect-error arbitrary object tokens are not registered builder.mock({}); // @ts-expect-error InjectionJS has no identifier metadata builder.mock(TOKEN, { tag: 'production' }); // @ts-expect-error a string token cannot be finalized with a number - builder.mock(CONFIG).final(42); + builder.final(CONFIG, 42); } void checkPublicTypes; diff --git a/e2e/esm/vitest/nestjs/abstract-tokens.e2e.test.ts b/e2e/esm/vitest/nestjs/abstract-tokens.e2e.test.ts index f4d171aa..b92bdcad 100644 --- a/e2e/esm/vitest/nestjs/abstract-tokens.e2e.test.ts +++ b/e2e/esm/vitest/nestjs/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/esm/vitest/nestjs/composition.e2e.test.ts b/e2e/esm/vitest/nestjs/composition.e2e.test.ts index 37b56720..b7c05491 100644 --- a/e2e/esm/vitest/nestjs/composition.e2e.test.ts +++ b/e2e/esm/vitest/nestjs/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/esm/vitest/nestjs/getters.e2e.test.ts b/e2e/esm/vitest/nestjs/getters.e2e.test.ts index 65562d32..1831ad23 100644 --- a/e2e/esm/vitest/nestjs/getters.e2e.test.ts +++ b/e2e/esm/vitest/nestjs/getters.e2e.test.ts @@ -23,20 +23,17 @@ class Application { describe('Supplied getter implementations', () => { it('configures a readonly getter through TestBed without assignment', async () => { let reads = 0; - const { unit, unitRef } = await TestBed.solitary(Application) - .mock(ConfigService) - .impl(() => ({ - get isCli() { - reads += 1; - return false; - }, - })) - .compile(); + const config = mock({ + get isCli() { + reads += 1; + return false; + }, + }); + const { unit } = await TestBed.solitary(Application).final(ConfigService, config).compile(); expect(reads).toBe(0); expect(unit.isCli()).toBe(false); expect(reads).toBe(1); - const config = unitRef.get(ConfigService); vi.spyOn(config, 'isCli', 'get').mockReturnValue(true); expect(unit.isCli()).toBe(true); }); diff --git a/e2e/esm/vitest/nestjs/suites-vitest-ctor-injection.e2e.test.ts b/e2e/esm/vitest/nestjs/suites-vitest-ctor-injection.e2e.test.ts index 8396167b..63463d2a 100644 --- a/e2e/esm/vitest/nestjs/suites-vitest-ctor-injection.e2e.test.ts +++ b/e2e/esm/vitest/nestjs/suites-vitest-ctor-injection.e2e.test.ts @@ -1,3 +1,4 @@ +import { mock } from '@suites/doubles.vitest'; import { beforeAll, describe, test, expect } from 'vitest'; import type { Mocked, UnitReference } from '@suites/unit'; import { TestBed } from '@suites/unit'; @@ -15,24 +16,17 @@ import { describe('Suites Vitest / NestJS E2E Test Ctor', () => { let unit: NestJSTestClass; let unitRef: UnitReference; + const testClassOne = mock(); beforeAll(async () => { + testClassOne.foo.mockResolvedValue('foo-from-test'); + testClassOne.bar.mockReturnValue('bar'); const { unitRef: ref, unit: underTest } = await TestBed.solitary(NestJSTestClass) - .mock(TestClassOne) - .impl((stunFn) => ({ - foo: stunFn().mockResolvedValue('foo-from-test'), - bar(): string { - return 'bar'; - }, - })) - .mock('CONSTANT_VALUE') - .final('arbitrary-string') - .mock('UNDEFINED') - .final({ method: () => 456 }) - .mock('LOGGER') - .final({ log: () => 'baz-from-test' }) - .mock(SymbolToken) - .final({ doSomething: () => 'mocked' }) + .final(TestClassOne, testClassOne) + .final('CONSTANT_VALUE', 'arbitrary-string') + .final('UNDEFINED', { method: () => 456 }) + .final('LOGGER', { log: () => 'baz-from-test' }) + .final(SymbolToken, { doSomething: () => 'mocked' }) .compile(); unitRef = ref; @@ -45,7 +39,7 @@ describe('Suites Vitest / NestJS E2E Test Ctor', () => { }); test('then successfully resolve the dependencies of the tested classes', () => { - expect(() => unitRef.get(TestClassOne)).toBeDefined(); + expect(() => unitRef.get(TestClassOne)).toThrow(/faked dependency/); }); test('call the unit instance method', async () => { @@ -58,14 +52,12 @@ describe('Suites Vitest / NestJS E2E Test Ctor', () => { }); test('then do not return the actual reflected dependencies of the injectable class', () => { - expect(() => unitRef.get(TestClassOne)).not.toBeInstanceOf(TestClassOne); + expect(testClassOne).not.toBeInstanceOf(TestClassOne); expect(() => unitRef.get(TestClassTwo)).not.toBeInstanceOf(TestClassTwo); expect(() => unitRef.get(SymbolToken)).not.toBeInstanceOf(TestClassFive); }); test('then mock the implementation of the dependencies', async () => { - const testClassOne: Mocked = unitRef.get(TestClassOne); - // The original 'foo' method in TestClassOne return value should be changed // according to the passed flag; here, always return the same value // because we mock the implementation of foo permanently diff --git a/e2e/esm/vitest/nestjs/type-safety.e2e.test.ts b/e2e/esm/vitest/nestjs/type-safety.e2e.test.ts index 3e586e2c..39ee2df2 100644 --- a/e2e/esm/vitest/nestjs/type-safety.e2e.test.ts +++ b/e2e/esm/vitest/nestjs/type-safety.e2e.test.ts @@ -5,8 +5,7 @@ import { NestJSTestClass } from './e2e-assets.js'; describe('NestJS DI Adapter Type Safety', () => { it('allows mocking without metadata', async () => { const { unitRef } = await TestBed.solitary(NestJSTestClass) - .mock('CONSTANT_VALUE') - .final('test-value') + .final('CONSTANT_VALUE', 'test-value') .compile(); expect(unitRef).toBeDefined(); diff --git a/e2e/jest/injection-js/abstract-tokens.e2e.test.ts b/e2e/jest/injection-js/abstract-tokens.e2e.test.ts index 42677623..370973e2 100644 --- a/e2e/jest/injection-js/abstract-tokens.e2e.test.ts +++ b/e2e/jest/injection-js/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/jest/injection-js/binding.e2e.test.ts b/e2e/jest/injection-js/binding.e2e.test.ts index 21278d81..0b5d8aea 100644 --- a/e2e/jest/injection-js/binding.e2e.test.ts +++ b/e2e/jest/injection-js/binding.e2e.test.ts @@ -1,5 +1,5 @@ import 'reflect-metadata'; -import { describe, expect, it, jest } from '@jest/globals'; +import { describe, expect, it } from '@jest/globals'; import { Inject, Injectable, InjectionToken } from 'injection-js'; import { TestBed } from '@suites/unit'; @@ -49,18 +49,17 @@ describe('v5 explicit token bindings', () => { it('rejects declarations for a different InjectionToken with the same description', async () => { const absent = new InjectionToken('repository'); - const configure = jest.fn(() => ({ read: () => 'unused' })); + const selector = TestBed.sociable(Root); for (const mode of [selector.expose(Leaf), selector]) { const bound = mode.bind(REPOSITORY, Repository); - await expect(bound.mock(absent).impl(configure).compile()).rejects.toMatchObject({ + await expect(bound.mock(absent).compile()).rejects.toMatchObject({ code: 'ER043', }); await expect(bound.bind(absent, Repository).compile()).rejects.toMatchObject({ code: 'ER043', }); } - expect(configure).not.toHaveBeenCalled(); }); it('recursively constructs the dependencies of a bound repository in composed mode', async () => { diff --git a/e2e/jest/injection-js/composition.e2e.test.ts b/e2e/jest/injection-js/composition.e2e.test.ts index ef9eb6af..ed81753c 100644 --- a/e2e/jest/injection-js/composition.e2e.test.ts +++ b/e2e/jest/injection-js/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/jest/injection-js/ctor-injection.e2e.test.ts b/e2e/jest/injection-js/ctor-injection.e2e.test.ts index 6597cbd3..3481e59a 100644 --- a/e2e/jest/injection-js/ctor-injection.e2e.test.ts +++ b/e2e/jest/injection-js/ctor-injection.e2e.test.ts @@ -46,8 +46,8 @@ describe('published InjectionJS adapter', () => { .forbid(TOKEN) .mock(OTHER) - .impl((stub) => ({ find: stub().mockReturnValue('replica') })) .compile(); + unitRef.get(OTHER).find.mockReturnValue('replica'); expect(unit.other.find()).toBe('replica'); expect(unitRef.get(OTHER).find).toHaveBeenCalledTimes(1); @@ -56,10 +56,8 @@ describe('published InjectionJS adapter', () => { it('distinguishes finalized and mocked tokens with identical descriptions', async () => { const { unit, unitRef } = await TestBed.solitary(Service) - .mock(TOKEN) - .final({ find: () => 'final' }) - .mock(CONFIG) - .final('test') + .final(TOKEN, { find: () => 'final' }) + .final(CONFIG, 'test') .compile(); expect(unit.token.find()).toBe('final'); expect(unit.other).toBe(unitRef.get(OTHER)); @@ -72,8 +70,7 @@ describe('published InjectionJS adapter', () => { constructor(@Optional() @Inject(TOKEN) readonly repository: Repository | null) {} } const { unit } = await TestBed.solitary(OptionalService) - .mock(TOKEN) - .final(null) + .final(TOKEN, null) .compile(); expect(unit.repository).toBeNull(); }); @@ -81,10 +78,9 @@ describe('published InjectionJS adapter', () => { it('mocks class, string, symbol and InjectionToken dependencies', async () => { const { unit, unitRef } = await TestBed.solitary(Service) .mock(TOKEN) - .impl((stub) => ({ find: stub().mockReturnValue('mock') })) - .mock(CONFIG) - .final('test') + .final(CONFIG, 'test') .compile(); + unitRef.get(TOKEN).find.mockReturnValue('mock'); const repository: Mocked = unitRef.get(Repository); repository.find.mockReturnValue('class mock'); expect(unit.repository.find()).toBe('class mock'); @@ -150,12 +146,12 @@ describe('published InjectionJS adapter', () => { // This function is checked by tsc without executing the intentionally invalid calls. function checkPublicTypes() { const builder = TestBed.solitary(Service); - builder.mock(TOKEN).impl((stub) => ({ find: stub().mockReturnValue('ok') })); + builder.mock(TOKEN); // @ts-expect-error arbitrary object tokens are not registered builder.mock({}); // @ts-expect-error InjectionJS has no identifier metadata builder.mock(TOKEN, { tag: 'production' }); // @ts-expect-error a string token cannot be finalized with a number - builder.mock(CONFIG).final(42); + builder.final(CONFIG, 42); } void checkPublicTypes; diff --git a/e2e/jest/injection-js/forbidden-boundaries.guard.test.ts b/e2e/jest/injection-js/forbidden-boundaries.guard.test.ts index 8da02658..66c5a606 100644 --- a/e2e/jest/injection-js/forbidden-boundaries.guard.test.ts +++ b/e2e/jest/injection-js/forbidden-boundaries.guard.test.ts @@ -91,8 +91,7 @@ it('rejects a mock and forbidden declaration for the same requested identifier', const compilation = TestBed.sociable(Checkout) .forbid(Boundary) - .mock(Boundary) - .final({ read: () => 'mocked' }) + .final(Boundary, { read: () => 'mocked' }) .compile(); await expect(compilation).rejects.toThrow(/conflicting.*Boundary/i); diff --git a/e2e/jest/inversify/abstract-tokens.e2e.test.ts b/e2e/jest/inversify/abstract-tokens.e2e.test.ts index 01065840..9ba39195 100644 --- a/e2e/jest/inversify/abstract-tokens.e2e.test.ts +++ b/e2e/jest/inversify/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); @@ -122,17 +114,17 @@ class NamedRepository { it('supports Inversify metadata with abstract tokens', async () => { const { unit, unitRef } = await TestBed.solitary(NamedRepository) .mock(Host, { named: 'primary' }) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) .compile(); + unitRef.get(Host, { named: 'primary' }).region.mockReturnValue('singapore'); const host = unitRef.get(Host, { named: 'primary' }); expect(unit.host).toBe(host); expect(host.region()).toBe('singapore'); const checkTypes = () => { // @ts-expect-error Abstract-token metadata lookups still infer Host.region's return type. host.region.mockReturnValue(42); - const override = TestBed.solitary(NamedRepository).mock(Host, { named: 'primary' }); + const builder = TestBed.solitary(NamedRepository); // @ts-expect-error Abstract-token metadata overrides still infer Host members. - override.final({ unknownMethod: () => 42 }); + builder.final(Host, { unknownMethod: () => 42 }, { named: 'primary' }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/jest/inversify/binding.e2e.test.ts b/e2e/jest/inversify/binding.e2e.test.ts index b8a773da..1cd294b9 100644 --- a/e2e/jest/inversify/binding.e2e.test.ts +++ b/e2e/jest/inversify/binding.e2e.test.ts @@ -82,17 +82,15 @@ describe('v5 explicit token bindings', () => { const replica = { named: 'replica' }; for (const mode of [selector.expose(Leaf), selector]) { const bound = mode.bind(REPOSITORY, Repository); - const mocked = await bound - .mock(REPOSITORY, replica) - .impl((stub) => ({ read: stub().mockReturnValue('mock replica') })) - .compile(); + const mocked = await bound.mock(REPOSITORY, replica).compile(); + mocked.unitRef.get(REPOSITORY, replica).read.mockReturnValue('mock replica'); expect(mocked.unit.replica.read()).toBe('mock replica'); expect(mocked.unitRef.get(REPOSITORY, replica).read).toHaveBeenCalledTimes(1); expect(mocked.unit.primary.read()).toBe('live:value'); expect(() => mocked.unitRef.get(REPOSITORY)).toThrow(/exposed dependency/); const supplied = { read: () => 'supplied replica' }; - const finalized = await bound.mock(REPOSITORY, replica).final(supplied).compile(); + const finalized = await bound.final(REPOSITORY, supplied, replica).compile(); expect(finalized.unit.replica).toBe(supplied); expect(finalized.unit.primary.read()).toBe('live:value'); } diff --git a/e2e/jest/inversify/composition.e2e.test.ts b/e2e/jest/inversify/composition.e2e.test.ts index d11a87a0..6a8e7e54 100644 --- a/e2e/jest/inversify/composition.e2e.test.ts +++ b/e2e/jest/inversify/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/jest/inversify/ctor-injection.e2e.test.ts b/e2e/jest/inversify/ctor-injection.e2e.test.ts index 37836234..a40c37c5 100644 --- a/e2e/jest/inversify/ctor-injection.e2e.test.ts +++ b/e2e/jest/inversify/ctor-injection.e2e.test.ts @@ -1,3 +1,4 @@ +import { mock } from '@suites/doubles.jest'; import 'reflect-metadata'; import type { UnitReference, Mocked } from '@suites/unit'; import { TestBed } from '@suites/unit'; @@ -18,28 +19,20 @@ import { describe('Suites Jest / InversifyJS E2E Test Ctor', () => { let unit: InversifyJSTestClass; let unitRef: UnitReference; + const testClassOne = mock(); beforeAll(async () => { + testClassOne.foo.mockResolvedValue('foo-from-test'); + testClassOne.bar.mockReturnValue('bar'); const { unitRef: ref, unit: underTest } = await TestBed.solitary( InversifyJSTestClass ) - .mock(TestClassOne) - .impl((stubFn) => ({ - foo: stubFn().mockResolvedValue('foo-from-test'), - bar(): string { - return 'bar'; - }, - })) - .mock('LOGGER') - .final({ log: () => 'baz-from-test' }) - .mock('UNDEFINED') - .final({ method: () => 456 }) - .mock('BarToken', { named: 'someTarget' }) - .final({}) - .mock('CONSTANT_VALUE') - .final('arbitrary-string') - .mock(SymbolToken) - .final({ doSomething: () => 'mocked' }) + .final(TestClassOne, testClassOne) + .final('LOGGER', { log: () => 'baz-from-test' }) + .final('UNDEFINED', { method: () => 456 }) + .final('BarToken', {}, { named: 'someTarget' }) + .final('CONSTANT_VALUE', 'arbitrary-string') + .final(SymbolToken, { doSomething: () => 'mocked' }) .compile(); unitRef = ref; @@ -60,7 +53,7 @@ describe('Suites Jest / InversifyJS E2E Test Ctor', () => { expect(() => unitRef.get(Foo)).toBeDefined(); expect(() => unitRef.get(TestClassTwo)).toBeDefined(); expect(() => unitRef.get('CONSTANT_VALUE')).toBeDefined(); - expect(() => unitRef.get(TestClassOne)).toBeDefined(); + expect(() => unitRef.get(TestClassOne)).toThrow(/faked dependency/); expect(() => unitRef.get(SymbolToken)).toBeDefined(); expect(() => unitRef.get(SymbolTokenSecond)).toBeDefined(); }); @@ -75,14 +68,12 @@ describe('Suites Jest / InversifyJS E2E Test Ctor', () => { }); test('then do not return the actual reflected dependencies of the injectable class', () => { - expect(() => unitRef.get(TestClassOne)).not.toBeInstanceOf(TestClassOne); + expect(testClassOne).not.toBeInstanceOf(TestClassOne); expect(() => unitRef.get(TestClassTwo)).not.toBeInstanceOf(TestClassTwo); expect(() => unitRef.get(SymbolToken)).not.toBeInstanceOf(TestClassFive); }); test('then mock the implementation of the dependencies', async () => { - const testClassOne: Mocked = unitRef.get(TestClassOne); - // The original 'foo' method in TestClassOne return value should be changed // according to the passed flag; here, always return the same value // because we mock the implementation of foo permanently diff --git a/e2e/jest/inversify/forbidden-boundaries.guard.test.ts b/e2e/jest/inversify/forbidden-boundaries.guard.test.ts index d6c36ec7..3c9679bd 100644 --- a/e2e/jest/inversify/forbidden-boundaries.guard.test.ts +++ b/e2e/jest/inversify/forbidden-boundaries.guard.test.ts @@ -110,8 +110,7 @@ it('rejects a mock and forbidden declaration for the same requested identifier', const compilation = TestBed.sociable(Checkout) .forbid(Boundary) - .mock(Boundary) - .final({ read: () => 'mocked' }) + .final(Boundary, { read: () => 'mocked' }) .compile(); await expect(compilation).rejects.toThrow(/conflicting.*Boundary/i); diff --git a/e2e/jest/inversify/qualified-dependencies.e2e.test.ts b/e2e/jest/inversify/qualified-dependencies.e2e.test.ts index 651889bf..68158b7d 100644 --- a/e2e/jest/inversify/qualified-dependencies.e2e.test.ts +++ b/e2e/jest/inversify/qualified-dependencies.e2e.test.ts @@ -18,8 +18,7 @@ class SingleConsumer { it('rejects final retrieval through both qualified and unique bare-token lookups', async () => { const supplied = { label: () => 'final' }; const { unit, unitRef } = await TestBed.solitary(SingleConsumer) - .mock(Provider, { named: 'primary' }) - .final(supplied) + .final(Provider, supplied, { named: 'primary' }) .compile(); expect(unit.provider).toBe(supplied); @@ -39,11 +38,10 @@ class DoubleConsumer { it('keeps named final and implementation overrides distinct for the same class', async () => { const supplied = { label: () => 'final' }; const { unit, unitRef } = await TestBed.solitary(DoubleConsumer) - .mock(Provider, { named: 'primary' }) - .final(supplied) + .final(Provider, supplied, { named: 'primary' }) .mock(Provider, { named: 'secondary' }) - .impl((stub) => ({ label: stub().mockReturnValue('mock') })) .compile(); + unitRef.get(Provider, { named: 'secondary' }).label.mockReturnValue('mock'); const mocked = unitRef.get(Provider, { named: 'secondary' }); expect(unit.primary).toBe(supplied); diff --git a/e2e/jest/inversify/strict-declarations.e2e.test.ts b/e2e/jest/inversify/strict-declarations.e2e.test.ts index 6a881ac1..d71e12f9 100644 --- a/e2e/jest/inversify/strict-declarations.e2e.test.ts +++ b/e2e/jest/inversify/strict-declarations.e2e.test.ts @@ -23,11 +23,10 @@ describe('sociable declaration validation', () => { const selector = () => TestBed.sociable(Root); it('rejects unreachable mocks, finals, bindings and exposures when compiling', async () => { - const configure = jest.fn(() => ({})); for (const mode of [selector().expose(Leaf), selector()]) { for (const declaration of [ - mode.mock(PORT, { named: 'absent' }).impl(configure), - mode.mock(OTHER).final({}), + mode.mock(PORT, { named: 'absent' }), + mode.final(OTHER, {}), mode.bind('absent', Leaf), ]) { await expect(declaration.compile()).rejects.toMatchObject({ code: 'ER043' }); @@ -40,20 +39,15 @@ describe('sociable declaration validation', () => { ).rejects.toMatchObject({ code: 'ER043', }); - expect(configure).toHaveBeenCalledTimes(0); }); - it('rejects two overrides that match the same qualified request before calling a factory', async () => { - const configure = jest.fn(() => ({})); + it('rejects two overrides that match the same qualified request before constructing the unit', async () => { for (const mode of [selector().expose(Leaf), selector()]) { - const primary = mode.mock(PORT, { named: 'primary' }).impl(configure); - await expect( - primary.mock(PORT, { named: 'primary' }).final({}).compile() - ).rejects.toMatchObject({ + const primary = mode.mock(PORT, { named: 'primary' }); + await expect(primary.final(PORT, {}, { named: 'primary' }).compile()).rejects.toMatchObject({ code: 'ER042', }); } - expect(configure).toHaveBeenCalledTimes(0); }); it('accepts distinct qualifiers and repeated identical declarations, even if a test never uses a dependency', async () => { @@ -61,10 +55,8 @@ describe('sociable declaration validation', () => { const primary = {}; const secondary = {}; const { unit } = await current - .mock(PORT, { named: 'primary' }) - .final(primary) - .mock(PORT, { named: 'secondary' }) - .final(secondary) + .final(PORT, primary, { named: 'primary' }) + .final(PORT, secondary, { named: 'secondary' }) .compile(); expect(unit.primary).toBe(primary); expect(unit.secondary).toBe(secondary); @@ -89,10 +81,8 @@ describe('sociable declaration validation', () => { const warning = jest.spyOn(nodeConsole, 'warn').mockImplementation(() => undefined); try { await TestBed.solitary(Root) - .mock(PORT, { named: 'primary' }) - .final({}) - .mock(PORT, { named: 'absent' }) - .final({}) + .final(PORT, {}, { named: 'primary' }) + .final(PORT, {}, { named: 'absent' }) .compile(); expect(warning).toHaveBeenCalledTimes(1); expect(warning).toHaveBeenCalledWith(expect.stringContaining('WR001')); diff --git a/e2e/jest/inversify/type-safety.e2e.test.ts b/e2e/jest/inversify/type-safety.e2e.test.ts index 7a50c4b6..e3f5e98b 100644 --- a/e2e/jest/inversify/type-safety.e2e.test.ts +++ b/e2e/jest/inversify/type-safety.e2e.test.ts @@ -5,8 +5,7 @@ import { InversifyJSTestClass, SymbolToken } from './e2e-assets'; describe('Inversify DI Adapter Type Safety', () => { it('allows metadata argument for string tokens', async () => { const { unitRef } = await TestBed.solitary(InversifyJSTestClass) - .mock('BarToken', { named: 'someTarget' }) - .final('value') + .final('BarToken', 'value', { named: 'someTarget' }) .compile(); expect(unitRef).toBeDefined(); @@ -14,8 +13,7 @@ describe('Inversify DI Adapter Type Safety', () => { it('allows metadata argument for symbol tokens', async () => { const { unitRef } = await TestBed.solitary(InversifyJSTestClass) - .mock(SymbolToken, { inject: 'someIdentifier' }) - .final('value') + .final(SymbolToken, 'value', { inject: 'someIdentifier' }) .compile(); expect(unitRef).toBeDefined(); @@ -23,8 +21,7 @@ describe('Inversify DI Adapter Type Safety', () => { it('works without metadata', async () => { const { unitRef } = await TestBed.solitary(InversifyJSTestClass) - .mock('CONSTANT_VALUE') - .final('value') + .final('CONSTANT_VALUE', 'value') .compile(); expect(unitRef).toBeDefined(); diff --git a/e2e/jest/nestjs/abstract-tokens.e2e.test.ts b/e2e/jest/nestjs/abstract-tokens.e2e.test.ts index a510b94e..a5063ee5 100644 --- a/e2e/jest/nestjs/abstract-tokens.e2e.test.ts +++ b/e2e/jest/nestjs/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/jest/nestjs/binding.e2e.test.ts b/e2e/jest/nestjs/binding.e2e.test.ts index c0d7d731..a590fbb7 100644 --- a/e2e/jest/nestjs/binding.e2e.test.ts +++ b/e2e/jest/nestjs/binding.e2e.test.ts @@ -144,17 +144,11 @@ describe('v5 explicit token bindings', () => { const selector = TestBed.sociable(Subject); for (const mode of [selector.expose(Leaf), selector]) { const bound = mode.bind(REPOSITORY, Repository); + await expect(bound.mock(REPOSITORY).compile()).rejects.toThrow( + /conflicting.*repository/i + ); await expect( - bound - .mock(REPOSITORY) - .impl((stub) => ({ read: stub() })) - .compile() - ).rejects.toThrow(/conflicting.*repository/i); - await expect( - bound - .mock(REPOSITORY) - .final({ read: () => 'supplied' }) - .compile() + bound.final(REPOSITORY, { read: () => 'supplied' }).compile() ).rejects.toThrow(/conflicting.*repository/i); } expect(constructions).toBe(0); diff --git a/e2e/jest/nestjs/composition.e2e.test.ts b/e2e/jest/nestjs/composition.e2e.test.ts index 95773fd4..53e33bdf 100644 --- a/e2e/jest/nestjs/composition.e2e.test.ts +++ b/e2e/jest/nestjs/composition.e2e.test.ts @@ -60,10 +60,8 @@ describe('default sociable composition', () => { const selective = TestBed.sociable(EmptyLeafRoot).expose(EmptyLeaf, AnotherEmptyLeaf); const composed = TestBed.sociable(Service); const exposed = await selective.compile(); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error All exposed classes are supplied in one call. expect(selective.expose).toBeUndefined(); // @ts-expect-error Selective mode excludes recursive composition. diff --git a/e2e/jest/nestjs/forbidden-boundaries.guard.test.ts b/e2e/jest/nestjs/forbidden-boundaries.guard.test.ts index 24db390a..ff55b03d 100644 --- a/e2e/jest/nestjs/forbidden-boundaries.guard.test.ts +++ b/e2e/jest/nestjs/forbidden-boundaries.guard.test.ts @@ -1,4 +1,7 @@ -import { DependencyVerification, subscribeDependencyViolationObserver } from '@suites/core.unit/verification'; +import { + DependencyVerification, + subscribeDependencyViolationObserver, +} from '@suites/core.unit/verification'; import 'reflect-metadata'; import { beforeEach, expect, it } from '@jest/globals'; import { Inject, Injectable } from '@nestjs/common'; @@ -119,8 +122,7 @@ it('rejects a mock and forbidden declaration for the same requested identifier', const compilation = TestBed.sociable(Checkout) .forbid(Boundary) - .mock(Boundary) - .final({ read: () => 'mocked' }) + .final(Boundary, { read: () => 'mocked' }) .compile(); await expect(compilation).rejects.toThrow(/conflicting.*Boundary/i); diff --git a/e2e/jest/nestjs/getters.e2e.test.ts b/e2e/jest/nestjs/getters.e2e.test.ts index d6f78f06..f36b9293 100644 --- a/e2e/jest/nestjs/getters.e2e.test.ts +++ b/e2e/jest/nestjs/getters.e2e.test.ts @@ -23,20 +23,17 @@ class Application { describe('Supplied getter implementations', () => { it('configures a readonly getter through TestBed without assignment', async () => { let reads = 0; - const { unit, unitRef } = await TestBed.solitary(Application) - .mock(ConfigService) - .impl(() => ({ - get isCli() { - reads += 1; - return false; - }, - })) - .compile(); + const config = mock({ + get isCli() { + reads += 1; + return false; + }, + }); + const { unit } = await TestBed.solitary(Application).final(ConfigService, config).compile(); expect(reads).toBe(0); expect(unit.isCli()).toBe(false); expect(reads).toBe(1); - const config = unitRef.get(ConfigService); jest.spyOn(config, 'isCli', 'get').mockReturnValue(true); expect(unit.isCli()).toBe(true); }); diff --git a/e2e/jest/nestjs/suites-jest-ctor-injection.e2e.test.ts b/e2e/jest/nestjs/suites-jest-ctor-injection.e2e.test.ts index 5b227a25..6bdc7b26 100644 --- a/e2e/jest/nestjs/suites-jest-ctor-injection.e2e.test.ts +++ b/e2e/jest/nestjs/suites-jest-ctor-injection.e2e.test.ts @@ -1,3 +1,4 @@ +import { mock } from '@suites/doubles.jest'; import type { UnitReference, Mocked } from '@suites/unit'; import { TestBed } from '@suites/unit'; import type { Logger, TestClassFive } from './e2e-assets'; @@ -13,27 +14,21 @@ import { describe('Suites Jest / NestJS E2E Test Ctor', () => { let unit: NestJSTestClass; let unitRef: UnitReference; + const testClassOne = mock(); beforeAll(async () => { + testClassOne.foo.mockResolvedValue('foo-from-test'); + testClassOne.bar.mockReturnValue('bar'); const { unitRef: ref, unit: underTest } = await TestBed.solitary( NestJSTestClass ) - .mock(TestClassOne) - .impl((stubFn) => ({ - foo: stubFn().mockResolvedValue('foo-from-test'), - bar(): string { - return 'bar'; - }, - })) - .mock('CONSTANT_VALUE') - .final('arbitrary-string') - .mock('UNDEFINED') - .final({ method: () => 456 }) + .final(TestClassOne, testClassOne) + .final('CONSTANT_VALUE', 'arbitrary-string') + .final('UNDEFINED', { method: () => 456 }) .mock('LOGGER') - .impl((stubFn) => ({ log: stubFn().mockReturnValue('baz-from-test') })) - .mock(SymbolToken) - .final({ doSomething: () => 'mocked' }) + .final(SymbolToken, { doSomething: () => 'mocked' }) .compile(); + ref.get('LOGGER').log.mockReturnValue('baz-from-test'); unitRef = ref; unit = underTest; @@ -46,7 +41,7 @@ describe('Suites Jest / NestJS E2E Test Ctor', () => { test('then successfully resolve the dependencies of the tested classes', () => { expect(() => unitRef.get<{ log: () => void }>('LOGGER')).toBeDefined(); - expect(() => unitRef.get(TestClassOne)).toBeDefined(); + expect(() => unitRef.get(TestClassOne)).toThrow(/faked dependency/); }); test('call the unit instance method', async () => { @@ -59,7 +54,6 @@ describe('Suites Jest / NestJS E2E Test Ctor', () => { }); test('then mock the implementation of the dependencies', async () => { - const testClassOne: Mocked = unitRef.get(TestClassOne); const logger = unitRef.get('LOGGER'); // The original 'foo' method in TestClassOne return value should be changed diff --git a/e2e/jest/nestjs/suites-jest-prop-injection.e2e.test.ts b/e2e/jest/nestjs/suites-jest-prop-injection.e2e.test.ts index 33387066..eb2b7c1f 100644 --- a/e2e/jest/nestjs/suites-jest-prop-injection.e2e.test.ts +++ b/e2e/jest/nestjs/suites-jest-prop-injection.e2e.test.ts @@ -1,4 +1,4 @@ -import type { UnitReference, Mocked, Stub } from '@suites/unit'; +import type { UnitReference, Mocked } from '@suites/unit'; import { TestBed } from '@suites/unit'; import type { Logger, TestClassFive } from './e2e-assets'; import { @@ -19,18 +19,12 @@ describe('Suites Jest / NestJS E2E Test Props', () => { NestJSTestClassProp ) .mock(TestClassOne) - .impl((stubFn: Stub) => ({ - foo: stubFn().mockResolvedValue('foo-from-test'), - })) - .mock('CONSTANT_VALUE') - .final('arbitrary-string') - .mock('UNDEFINED') - .final({ method: () => 456 }) - .mock('LOGGER') - .final({ log: () => 'baz-from-test' }) - .mock(SymbolToken) - .final({ doSomething: () => 'mocked' }) + .final('CONSTANT_VALUE', 'arbitrary-string') + .final('UNDEFINED', { method: () => 456 }) + .final('LOGGER', { log: () => 'baz-from-test' }) + .final(SymbolToken, { doSomething: () => 'mocked' }) .compile(); + ref.get(TestClassOne).foo.mockResolvedValue('foo-from-test'); // For type checking only, no runtime effect // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/e2e/jest/nestjs/suites-jest-sociable-empty-constructor.e2e.test.ts b/e2e/jest/nestjs/suites-jest-sociable-empty-constructor.e2e.test.ts index 8a780314..9bba1c8e 100644 --- a/e2e/jest/nestjs/suites-jest-sociable-empty-constructor.e2e.test.ts +++ b/e2e/jest/nestjs/suites-jest-sociable-empty-constructor.e2e.test.ts @@ -10,7 +10,6 @@ describe('Suites Jest / NestJS E2E Test Ctor - Empty Constructor', () => { const { unit, unitRef } = await TestBed.sociable(TestService) .expose(TestSociableService) .mock(TestDependService) - .impl((stub) => ({ call: stub() })) .compile(); const testDependService = unitRef.get(TestDependService); diff --git a/e2e/jest/nestjs/suites-jest-sociable.e2e.test.ts b/e2e/jest/nestjs/suites-jest-sociable.e2e.test.ts index d0356255..d53ed4e2 100644 --- a/e2e/jest/nestjs/suites-jest-sociable.e2e.test.ts +++ b/e2e/jest/nestjs/suites-jest-sociable.e2e.test.ts @@ -19,16 +19,12 @@ describe('Suites Jest / NestJS E2E Test Ctor', () => { const { unitRef: ref, unit } = await TestBed.sociable(UserService) .expose(UserApiService, UserDal, DatabaseService) .mock(UserVerificationService) - .impl(() => ({})) .mock(ApiService) - .impl(() => ({})) .mock('Repository') - .impl(() => ({})) .mock(Logger) - .impl((stubFn) => ({ log: stubFn().mockReturnValue('overridden') })) - .mock('SOME_VALUE_TOKEN') - .final(['1', '2', '3']) + .final('SOME_VALUE_TOKEN', ['1', '2', '3']) .compile(); + ref.get(Logger).log.mockReturnValue('overridden'); // For type checking only, no runtime effect // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/e2e/jest/nestjs/type-safety.e2e.test.ts b/e2e/jest/nestjs/type-safety.e2e.test.ts index 6b913805..619171ee 100644 --- a/e2e/jest/nestjs/type-safety.e2e.test.ts +++ b/e2e/jest/nestjs/type-safety.e2e.test.ts @@ -4,8 +4,7 @@ import { NestJSTestClass } from './e2e-assets'; describe('NestJS DI Adapter Type Safety', () => { it('allows mocking without metadata', async () => { const { unitRef } = await TestBed.solitary(NestJSTestClass) - .mock('CONSTANT_VALUE') - .final('test-value') + .final('CONSTANT_VALUE', 'test-value') .compile(); expect(unitRef).toBeDefined(); diff --git a/e2e/vitest/injection-js/abstract-tokens.e2e.test.ts b/e2e/vitest/injection-js/abstract-tokens.e2e.test.ts index 7310522b..67a811f2 100644 --- a/e2e/vitest/injection-js/abstract-tokens.e2e.test.ts +++ b/e2e/vitest/injection-js/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/vitest/injection-js/composition.e2e.test.ts b/e2e/vitest/injection-js/composition.e2e.test.ts index cfe3dbd6..d092506e 100644 --- a/e2e/vitest/injection-js/composition.e2e.test.ts +++ b/e2e/vitest/injection-js/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/vitest/injection-js/ctor-injection.e2e.test.ts b/e2e/vitest/injection-js/ctor-injection.e2e.test.ts index a9248658..b916c14e 100644 --- a/e2e/vitest/injection-js/ctor-injection.e2e.test.ts +++ b/e2e/vitest/injection-js/ctor-injection.e2e.test.ts @@ -43,10 +43,8 @@ class Service { describe('published InjectionJS adapter', () => { it('distinguishes finalized and mocked tokens with identical descriptions', async () => { const { unit, unitRef } = await TestBed.solitary(Service) - .mock(TOKEN) - .final({ find: () => 'final' }) - .mock(CONFIG) - .final('test') + .final(TOKEN, { find: () => 'final' }) + .final(CONFIG, 'test') .compile(); expect(unit.token.find()).toBe('final'); expect(unit.other).toBe(unitRef.get(OTHER)); @@ -59,8 +57,7 @@ describe('published InjectionJS adapter', () => { constructor(@Optional() @Inject(TOKEN) readonly repository: Repository | null) {} } const { unit } = await TestBed.solitary(OptionalService) - .mock(TOKEN) - .final(null) + .final(TOKEN, null) .compile(); expect(unit.repository).toBeNull(); }); @@ -68,10 +65,9 @@ describe('published InjectionJS adapter', () => { it('mocks class, string, symbol and InjectionToken dependencies', async () => { const { unit, unitRef } = await TestBed.solitary(Service) .mock(TOKEN) - .impl((stub) => ({ find: stub().mockReturnValue('mock') })) - .mock(CONFIG) - .final('test') + .final(CONFIG, 'test') .compile(); + unitRef.get(TOKEN).find.mockReturnValue('mock'); const repository: Mocked = unitRef.get(Repository); repository.find.mockReturnValue('class mock'); expect(unit.repository.find()).toBe('class mock'); @@ -137,12 +133,12 @@ describe('published InjectionJS adapter', () => { // This function is checked by tsc without executing the intentionally invalid calls. function checkPublicTypes() { const builder = TestBed.solitary(Service); - builder.mock(TOKEN).impl((stub) => ({ find: stub().mockReturnValue('ok') })); + builder.mock(TOKEN); // @ts-expect-error arbitrary object tokens are not registered builder.mock({}); // @ts-expect-error InjectionJS has no identifier metadata builder.mock(TOKEN, { tag: 'production' }); // @ts-expect-error a string token cannot be finalized with a number - builder.mock(CONFIG).final(42); + builder.final(CONFIG, 42); } void checkPublicTypes; diff --git a/e2e/vitest/injection-js/forbidden-boundaries.guard.test.ts b/e2e/vitest/injection-js/forbidden-boundaries.guard.test.ts index 9d2b06f5..c737b11e 100644 --- a/e2e/vitest/injection-js/forbidden-boundaries.guard.test.ts +++ b/e2e/vitest/injection-js/forbidden-boundaries.guard.test.ts @@ -91,8 +91,7 @@ it('rejects a mock and forbidden declaration for the same requested identifier', const compilation = TestBed.sociable(Checkout) .forbid(Boundary) - .mock(Boundary) - .final({ read: () => 'mocked' }) + .final(Boundary, { read: () => 'mocked' }) .compile(); await expect(compilation).rejects.toThrow(/conflicting.*Boundary/i); diff --git a/e2e/vitest/inversify/abstract-tokens.e2e.test.ts b/e2e/vitest/inversify/abstract-tokens.e2e.test.ts index 6d346407..5201b477 100644 --- a/e2e/vitest/inversify/abstract-tokens.e2e.test.ts +++ b/e2e/vitest/inversify/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); @@ -122,17 +114,17 @@ class NamedRepository { it('supports Inversify metadata with abstract tokens', async () => { const { unit, unitRef } = await TestBed.solitary(NamedRepository) .mock(Host, { named: 'primary' }) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) .compile(); + unitRef.get(Host, { named: 'primary' }).region.mockReturnValue('singapore'); const host = unitRef.get(Host, { named: 'primary' }); expect(unit.host).toBe(host); expect(host.region()).toBe('singapore'); const checkTypes = () => { // @ts-expect-error Abstract-token metadata lookups still infer Host.region's return type. host.region.mockReturnValue(42); - const override = TestBed.solitary(NamedRepository).mock(Host, { named: 'primary' }); + const builder = TestBed.solitary(NamedRepository); // @ts-expect-error Abstract-token metadata overrides still infer Host members. - override.final({ unknownMethod: () => 42 }); + builder.final(Host, { unknownMethod: () => 42 }, { named: 'primary' }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/vitest/inversify/binding.e2e.test.ts b/e2e/vitest/inversify/binding.e2e.test.ts index 9087b8e7..7218e554 100644 --- a/e2e/vitest/inversify/binding.e2e.test.ts +++ b/e2e/vitest/inversify/binding.e2e.test.ts @@ -62,17 +62,15 @@ describe('v5 explicit token bindings', () => { const replica = { named: 'replica' }; for (const mode of [selector.expose(Leaf), selector]) { const bound = mode.bind(REPOSITORY, Repository); - const mocked = await bound - .mock(REPOSITORY, replica) - .impl((stub) => ({ read: stub().mockReturnValue('mock replica') })) - .compile(); + const mocked = await bound.mock(REPOSITORY, replica).compile(); + mocked.unitRef.get(REPOSITORY, replica).read.mockReturnValue('mock replica'); expect(mocked.unit.replica.read()).toBe('mock replica'); expect(mocked.unitRef.get(REPOSITORY, replica).read).toHaveBeenCalledTimes(1); expect(mocked.unit.primary.read()).toBe('live:value'); expect(() => mocked.unitRef.get(REPOSITORY)).toThrow(/exposed dependency/); const supplied = { read: () => 'supplied replica' }; - const finalized = await bound.mock(REPOSITORY, replica).final(supplied).compile(); + const finalized = await bound.final(REPOSITORY, supplied, replica).compile(); expect(finalized.unit.replica).toBe(supplied); expect(finalized.unit.primary.read()).toBe('live:value'); } diff --git a/e2e/vitest/inversify/composition.e2e.test.ts b/e2e/vitest/inversify/composition.e2e.test.ts index b162f276..d9e4c4fd 100644 --- a/e2e/vitest/inversify/composition.e2e.test.ts +++ b/e2e/vitest/inversify/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/vitest/inversify/ctor-injection.e2e.test.ts b/e2e/vitest/inversify/ctor-injection.e2e.test.ts index b63660c6..774a74e2 100644 --- a/e2e/vitest/inversify/ctor-injection.e2e.test.ts +++ b/e2e/vitest/inversify/ctor-injection.e2e.test.ts @@ -1,3 +1,4 @@ +import { mock } from '@suites/doubles.vitest'; import 'reflect-metadata'; import { beforeAll, describe, test, expect } from 'vitest'; import type { UnitReference, Mocked } from '@suites/unit'; @@ -17,28 +18,20 @@ import { describe('Suites Vitest / InversifyJS E2E Test Ctor', () => { let unit: InversifyJSTestClass; let unitRef: UnitReference; + const testClassOne = mock(); beforeAll(async () => { + testClassOne.foo.mockResolvedValue('foo-from-test'); + testClassOne.bar.mockReturnValue('bar'); const { unitRef: ref, unit: underTest } = await TestBed.solitary( InversifyJSTestClass ) - .mock(TestClassOne) - .impl((stubFn) => ({ - foo: stubFn().mockResolvedValue('foo-from-test'), - bar(): string { - return 'bar'; - }, - })) - .mock('LOGGER') - .final({ log: () => 'baz-from-test' }) - .mock('UNDEFINED') - .final({ method: () => 456 }) - .mock('BarToken', { named: 'someTarget' }) - .final({}) - .mock('CONSTANT_VALUE') - .final('arbitrary-string') - .mock(SymbolToken) - .final({ doSomething: () => 'mocked' }) + .final(TestClassOne, testClassOne) + .final('LOGGER', { log: () => 'baz-from-test' }) + .final('UNDEFINED', { method: () => 456 }) + .final('BarToken', {}, { named: 'someTarget' }) + .final('CONSTANT_VALUE', 'arbitrary-string') + .final(SymbolToken, { doSomething: () => 'mocked' }) .compile(); unitRef = ref; @@ -52,7 +45,7 @@ describe('Suites Vitest / InversifyJS E2E Test Ctor', () => { test('then successfully resolve the dependencies of the tested classes', () => { expect(() => unitRef.get(TestClassTwo)).toBeDefined(); - expect(() => unitRef.get(TestClassOne)).toBeDefined(); + expect(() => unitRef.get(TestClassOne)).toThrow(/faked dependency/); }); test('call the unit instance method', async () => { @@ -65,14 +58,12 @@ describe('Suites Vitest / InversifyJS E2E Test Ctor', () => { }); test('then do not return the actual reflected dependencies of the injectable class', () => { - expect(() => unitRef.get(TestClassOne)).not.toBeInstanceOf(TestClassOne); + expect(testClassOne).not.toBeInstanceOf(TestClassOne); expect(() => unitRef.get(TestClassTwo)).not.toBeInstanceOf(TestClassTwo); expect(() => unitRef.get(SymbolToken)).not.toBeInstanceOf(TestClassFive); }); test('then mock the implementation of the dependencies', async () => { - const testClassOne: Mocked = unitRef.get(TestClassOne); - // The original 'foo' method in TestClassOne return value should be changed // according to the passed flag; here, always return the same value // because we mock the implementation of foo permanently diff --git a/e2e/vitest/inversify/forbidden-boundaries.guard.test.ts b/e2e/vitest/inversify/forbidden-boundaries.guard.test.ts index 21e29688..fda286ba 100644 --- a/e2e/vitest/inversify/forbidden-boundaries.guard.test.ts +++ b/e2e/vitest/inversify/forbidden-boundaries.guard.test.ts @@ -110,8 +110,7 @@ it('rejects a mock and forbidden declaration for the same requested identifier', const compilation = TestBed.sociable(Checkout) .forbid(Boundary) - .mock(Boundary) - .final({ read: () => 'mocked' }) + .final(Boundary, { read: () => 'mocked' }) .compile(); await expect(compilation).rejects.toThrow(/conflicting.*Boundary/i); diff --git a/e2e/vitest/inversify/qualified-dependencies.e2e.test.ts b/e2e/vitest/inversify/qualified-dependencies.e2e.test.ts index 30dbc90f..7ef80bbb 100644 --- a/e2e/vitest/inversify/qualified-dependencies.e2e.test.ts +++ b/e2e/vitest/inversify/qualified-dependencies.e2e.test.ts @@ -18,8 +18,7 @@ class SingleConsumer { it('rejects final retrieval through both qualified and unique bare-token lookups', async () => { const supplied = { label: () => 'final' }; const { unit, unitRef } = await TestBed.solitary(SingleConsumer) - .mock(Provider, { named: 'primary' }) - .final(supplied) + .final(Provider, supplied, { named: 'primary' }) .compile(); expect(unit.provider).toBe(supplied); @@ -39,11 +38,10 @@ class DoubleConsumer { it('keeps named final and implementation overrides distinct for the same class', async () => { const supplied = { label: () => 'final' }; const { unit, unitRef } = await TestBed.solitary(DoubleConsumer) - .mock(Provider, { named: 'primary' }) - .final(supplied) + .final(Provider, supplied, { named: 'primary' }) .mock(Provider, { named: 'secondary' }) - .impl((stub) => ({ label: stub().mockReturnValue('mock') })) .compile(); + unitRef.get(Provider, { named: 'secondary' }).label.mockReturnValue('mock'); const mocked = unitRef.get(Provider, { named: 'secondary' }); expect(unit.primary).toBe(supplied); diff --git a/e2e/vitest/inversify/type-safety.e2e.test.ts b/e2e/vitest/inversify/type-safety.e2e.test.ts index 53ee2ce5..d35f17ae 100644 --- a/e2e/vitest/inversify/type-safety.e2e.test.ts +++ b/e2e/vitest/inversify/type-safety.e2e.test.ts @@ -6,8 +6,7 @@ import { InversifyJSTestClass, SymbolToken } from './e2e-assets.js'; describe('Inversify DI Adapter Type Safety', () => { it('allows metadata argument for string tokens', async () => { const { unitRef } = await TestBed.solitary(InversifyJSTestClass) - .mock('BarToken', { named: 'someTarget' }) - .final('value') + .final('BarToken', 'value', { named: 'someTarget' }) .compile(); expect(unitRef).toBeDefined(); @@ -15,8 +14,7 @@ describe('Inversify DI Adapter Type Safety', () => { it('allows metadata argument for symbol tokens', async () => { const { unitRef } = await TestBed.solitary(InversifyJSTestClass) - .mock(SymbolToken, { inject: 'someIdentifier' }) - .final('value') + .final(SymbolToken, 'value', { inject: 'someIdentifier' }) .compile(); expect(unitRef).toBeDefined(); @@ -24,8 +22,7 @@ describe('Inversify DI Adapter Type Safety', () => { it('works without metadata', async () => { const { unitRef } = await TestBed.solitary(InversifyJSTestClass) - .mock('CONSTANT_VALUE') - .final('value') + .final('CONSTANT_VALUE', 'value') .compile(); expect(unitRef).toBeDefined(); diff --git a/e2e/vitest/nestjs/abstract-tokens.e2e.test.ts b/e2e/vitest/nestjs/abstract-tokens.e2e.test.ts index f4d171aa..b92bdcad 100644 --- a/e2e/vitest/nestjs/abstract-tokens.e2e.test.ts +++ b/e2e/vitest/nestjs/abstract-tokens.e2e.test.ts @@ -55,20 +55,15 @@ describe('abstract class dependency tokens', () => { it('accepts a concrete implementation for an abstract token', async () => { const supplied = new MockHost('singapore'); - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .final(supplied) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).final(Host, supplied).compile(); expect(unit.host).toBe(supplied); expect(unit.readRegion()).toBe('singapore'); expect(() => unitRef.get(Host)).toThrow(/faked dependency/); }); it('infers the abstract dependency when configuring an implementation', async () => { - const { unit, unitRef } = await TestBed.solitary(Repository) - .mock(Host) - .impl((stub) => ({ region: stub().mockReturnValue('singapore') })) - .compile(); + const { unit, unitRef } = await TestBed.solitary(Repository).mock(Host).compile(); + unitRef.get(Host).region.mockReturnValue('singapore'); const host = unitRef.get(Host); expect(unit.readRegion()).toBe('singapore'); host.region.mockReturnValue('london'); @@ -79,7 +74,6 @@ describe('abstract class dependency tokens', () => { const { unit, unitRef } = await TestBed.sociable(Service) .expose(Repository) .mock(Host) - .impl((stub) => ({ region: stub() })) .compile(); unitRef.get(Host).region.mockReturnValue('singapore'); expect(unit.repository).toBeInstanceOf(Repository); @@ -104,11 +98,9 @@ describe('abstract class dependency tokens', () => { TestBed.sociable(Host); // @ts-expect-error Exposed classes must be concrete. TestBed.sociable(Service).expose(Host); - const override = TestBed.solitary(Repository).mock(Host); + const builder = TestBed.solitary(Repository); // @ts-expect-error Final overrides infer Host and reject unrelated properties. - override.final({ unknownMethod: () => 42 }); - // @ts-expect-error Implementation callbacks infer Host and reject unrelated properties. - override.impl(() => ({ unknownMethod: () => 42 })); + builder.final(Host, { unknownMethod: () => 42 }); }; expect(checkTypes).toBeDefined(); }); diff --git a/e2e/vitest/nestjs/composition.e2e.test.ts b/e2e/vitest/nestjs/composition.e2e.test.ts index 37b56720..b7c05491 100644 --- a/e2e/vitest/nestjs/composition.e2e.test.ts +++ b/e2e/vitest/nestjs/composition.e2e.test.ts @@ -43,10 +43,8 @@ describe('default sociable composition', () => { it('retains explicit override chains and excludes selective exposure', async () => { const composed = TestBed.sociable(Service); const selective = TestBed.sociable(Service).expose(Repository); - const overridden = await composed - .mock(Leaf) - .impl((stub) => ({ prefix: stub().mockReturnValue('mock:') })) - .compile(); + const overridden = await composed.mock(Leaf).compile(); + overridden.unitRef.get(Leaf).prefix.mockReturnValue('mock:'); // @ts-expect-error Choose selective exposure before declaring a boundary. const invalidExpose = composed.forbid(Leaf).expose; // @ts-expect-error All exposed classes are supplied in one call. diff --git a/e2e/vitest/nestjs/forbidden-boundaries.guard.test.ts b/e2e/vitest/nestjs/forbidden-boundaries.guard.test.ts index 18c6d7d6..bbf847db 100644 --- a/e2e/vitest/nestjs/forbidden-boundaries.guard.test.ts +++ b/e2e/vitest/nestjs/forbidden-boundaries.guard.test.ts @@ -111,8 +111,7 @@ it('rejects a mock and forbidden declaration for the same requested identifier', const compilation = TestBed.sociable(Checkout) .forbid(Boundary) - .mock(Boundary) - .final({ read: () => 'mocked' }) + .final(Boundary, { read: () => 'mocked' }) .compile(); await expect(compilation).rejects.toThrow(/conflicting.*Boundary/i); diff --git a/e2e/vitest/nestjs/getters.e2e.test.ts b/e2e/vitest/nestjs/getters.e2e.test.ts index 65562d32..1831ad23 100644 --- a/e2e/vitest/nestjs/getters.e2e.test.ts +++ b/e2e/vitest/nestjs/getters.e2e.test.ts @@ -23,20 +23,17 @@ class Application { describe('Supplied getter implementations', () => { it('configures a readonly getter through TestBed without assignment', async () => { let reads = 0; - const { unit, unitRef } = await TestBed.solitary(Application) - .mock(ConfigService) - .impl(() => ({ - get isCli() { - reads += 1; - return false; - }, - })) - .compile(); + const config = mock({ + get isCli() { + reads += 1; + return false; + }, + }); + const { unit } = await TestBed.solitary(Application).final(ConfigService, config).compile(); expect(reads).toBe(0); expect(unit.isCli()).toBe(false); expect(reads).toBe(1); - const config = unitRef.get(ConfigService); vi.spyOn(config, 'isCli', 'get').mockReturnValue(true); expect(unit.isCli()).toBe(true); }); diff --git a/e2e/vitest/nestjs/suites-vitest-ctor-injection.e2e.test.ts b/e2e/vitest/nestjs/suites-vitest-ctor-injection.e2e.test.ts index 8396167b..63463d2a 100644 --- a/e2e/vitest/nestjs/suites-vitest-ctor-injection.e2e.test.ts +++ b/e2e/vitest/nestjs/suites-vitest-ctor-injection.e2e.test.ts @@ -1,3 +1,4 @@ +import { mock } from '@suites/doubles.vitest'; import { beforeAll, describe, test, expect } from 'vitest'; import type { Mocked, UnitReference } from '@suites/unit'; import { TestBed } from '@suites/unit'; @@ -15,24 +16,17 @@ import { describe('Suites Vitest / NestJS E2E Test Ctor', () => { let unit: NestJSTestClass; let unitRef: UnitReference; + const testClassOne = mock(); beforeAll(async () => { + testClassOne.foo.mockResolvedValue('foo-from-test'); + testClassOne.bar.mockReturnValue('bar'); const { unitRef: ref, unit: underTest } = await TestBed.solitary(NestJSTestClass) - .mock(TestClassOne) - .impl((stunFn) => ({ - foo: stunFn().mockResolvedValue('foo-from-test'), - bar(): string { - return 'bar'; - }, - })) - .mock('CONSTANT_VALUE') - .final('arbitrary-string') - .mock('UNDEFINED') - .final({ method: () => 456 }) - .mock('LOGGER') - .final({ log: () => 'baz-from-test' }) - .mock(SymbolToken) - .final({ doSomething: () => 'mocked' }) + .final(TestClassOne, testClassOne) + .final('CONSTANT_VALUE', 'arbitrary-string') + .final('UNDEFINED', { method: () => 456 }) + .final('LOGGER', { log: () => 'baz-from-test' }) + .final(SymbolToken, { doSomething: () => 'mocked' }) .compile(); unitRef = ref; @@ -45,7 +39,7 @@ describe('Suites Vitest / NestJS E2E Test Ctor', () => { }); test('then successfully resolve the dependencies of the tested classes', () => { - expect(() => unitRef.get(TestClassOne)).toBeDefined(); + expect(() => unitRef.get(TestClassOne)).toThrow(/faked dependency/); }); test('call the unit instance method', async () => { @@ -58,14 +52,12 @@ describe('Suites Vitest / NestJS E2E Test Ctor', () => { }); test('then do not return the actual reflected dependencies of the injectable class', () => { - expect(() => unitRef.get(TestClassOne)).not.toBeInstanceOf(TestClassOne); + expect(testClassOne).not.toBeInstanceOf(TestClassOne); expect(() => unitRef.get(TestClassTwo)).not.toBeInstanceOf(TestClassTwo); expect(() => unitRef.get(SymbolToken)).not.toBeInstanceOf(TestClassFive); }); test('then mock the implementation of the dependencies', async () => { - const testClassOne: Mocked = unitRef.get(TestClassOne); - // The original 'foo' method in TestClassOne return value should be changed // according to the passed flag; here, always return the same value // because we mock the implementation of foo permanently diff --git a/e2e/vitest/nestjs/type-safety.e2e.test.ts b/e2e/vitest/nestjs/type-safety.e2e.test.ts index 3e586e2c..39ee2df2 100644 --- a/e2e/vitest/nestjs/type-safety.e2e.test.ts +++ b/e2e/vitest/nestjs/type-safety.e2e.test.ts @@ -5,8 +5,7 @@ import { NestJSTestClass } from './e2e-assets.js'; describe('NestJS DI Adapter Type Safety', () => { it('allows mocking without metadata', async () => { const { unitRef } = await TestBed.solitary(NestJSTestClass) - .mock('CONSTANT_VALUE') - .final('test-value') + .final('CONSTANT_VALUE', 'test-value') .compile(); expect(unitRef).toBeDefined(); From 4a373428c5946cf40b7245637380d0d6888c8952 Mon Sep 17 00:00:00 2001 From: omermorad Date: Sat, 28 Nov 2026 23:12:06 +0200 Subject: [PATCH 3/8] test(unit): check packed declarations for direct mock and final boundaries --- .../release-type-compatibility/v5/core.ts | 26 ++++------- .../release-type-compatibility/v5/emitted.ts | 43 ++++++++----------- .../release-type-compatibility/v5/fluent.ts | 20 ++++----- .../release-type-compatibility/v5/helpers.ts | 2 +- .../v5/public-builder-types.ts | 30 +++++++------ 5 files changed, 50 insertions(+), 71 deletions(-) diff --git a/scripts/fixtures/release-type-compatibility/v5/core.ts b/scripts/fixtures/release-type-compatibility/v5/core.ts index 1b850af2..cecd3a51 100644 --- a/scripts/fixtures/release-type-compatibility/v5/core.ts +++ b/scripts/fixtures/release-type-compatibility/v5/core.ts @@ -6,7 +6,9 @@ import type { SuitesWarningCode } from '@suites/types.common'; import type {} from '@suites/doubles.jest/unit'; import { SociableTestBedBuilder, SolitaryTestBedBuilder, UnitMocker } from '@suites/core.unit'; -import type { MockOverride, TestBedBuilder } from '@suites/core.unit'; +import type { TestBedBuilder } from '@suites/core.unit'; +// @ts-expect-error v5 removed the override selector. +import type { MockOverride } from '@suites/core.unit'; import type { Type } from '@suites/types.common'; import type { DependencyInjectionAdapter } from '@suites/types.di'; import type { DoublesAdapter } from '@suites/types.doubles'; @@ -41,26 +43,14 @@ class CustomBuilder extends SociableTestBedBuilder { } } -function configure(builder: TestBedBuilder): MockOverride { +function configure(builder: TestBedBuilder): TestBedBuilder { return builder.mock(Service); } -sociable - .expose(Service) - .mock(Service) - .final({ read: () => 'selective' }) - .compile(); -sociable - .mock(Service) - .final({ read: () => 'composed' }) - .compile(); -solitary - .mock(Service) - .final({ read: () => 'solitary' }) - .compile(); -configure(solitary) - .impl((stub) => ({ read: stub().mockReturnValue('configured') })) - .compile(); +sociable.expose(Service).mock('clock').compile(); +sociable.final(Service, { read: () => 'composed' }).compile(); +solitary.final(Service, { read: () => 'solitary' }).compile(); +configure(solitary).compile(); void CustomBuilder; diff --git a/scripts/fixtures/release-type-compatibility/v5/emitted.ts b/scripts/fixtures/release-type-compatibility/v5/emitted.ts index 4dc75fb3..a7ed2306 100644 --- a/scripts/fixtures/release-type-compatibility/v5/emitted.ts +++ b/scripts/fixtures/release-type-compatibility/v5/emitted.ts @@ -1,34 +1,25 @@ import type {} from '@suites/doubles.jest/unit'; -import { Service, composed, selective, selector, sociable, solitary } from './declarations/helpers'; +import { Service, composed, selective, sociable, solitary, withMock } from './declarations/helpers'; -solitary() - .mock(Service) - .final({ read: () => 'solitary' }) - .compile(); +const supplied = { name: 'supplied', read: () => 'value' } satisfies Service; + +solitary().final(Service, supplied).compile(); sociable().compile(); -selective() - .mock(Service) - .final({ read: () => 'selective' }) - .compile(); -composed() - .mock(Service) - .final({ read: () => 'composed' }) - .compile(); -selector() - .final({ read: () => 'selected' }) - .compile(); +selective().mock('gateway').compile(); +composed().final(Service, supplied).compile(); +withMock().compile(); +withMock().forbid('external').compile(); +withMock().final('config', { retries: 3 }).compile(); // @ts-expect-error Emitted selective declarations do not expose compose(). selective().compose(); -// @ts-expect-error Emitted composed declarations do not expose expose(). +// @ts-expect-error Configured composition cannot switch to selective exposure. composed().expose(Service); -// @ts-expect-error Emitted declarations preserve the dependency type. -selector().final({ name: 1 }); - -composed().forbid(Service).compile(); -selector() - .final({ read: () => 'selected' }) - .forbid(Service) - .compile(); -// @ts-expect-error Only composed builders support forbid(). +// @ts-expect-error Emitted declarations preserve the dependency's public value type. +withMock().final(Service, { name: 1, read: () => 'value' }); +// @ts-expect-error Generated mocks have no implementation selector. +withMock().impl(() => ({})); +// @ts-expect-error A final declaration requires both an identifier and a value. +withMock().final(supplied); +// @ts-expect-error Only recursive composition supports forbid(). selective().forbid(Service); diff --git a/scripts/fixtures/release-type-compatibility/v5/fluent.ts b/scripts/fixtures/release-type-compatibility/v5/fluent.ts index 43ecf5e8..b0cf5b5e 100644 --- a/scripts/fixtures/release-type-compatibility/v5/fluent.ts +++ b/scripts/fixtures/release-type-compatibility/v5/fluent.ts @@ -14,13 +14,8 @@ class Subject { } } -const selective = TestBed.sociable(Subject) - .expose(Service) - .mock(Service) - .impl((stub) => ({ read: stub().mockReturnValue('yes') })); -const composed = TestBed.sociable(Subject) - .mock(Service) - .final({ read: () => 'yes' }); +const selective = TestBed.sociable(Subject).expose(Service).mock('gateway'); +const composed = TestBed.sociable(Subject).mock(Service); // @ts-expect-error Selective mode does not expose compose(). selective.compose(); @@ -44,10 +39,11 @@ declare const token: ServiceToken; const initial = TestBed.sociable(Subject); initial.bind(token, Service); for (const mode of [initial.expose(Service), initial]) { - mode - .bind(token, Service) - .mock(token) - .final({ read: () => 'stub' }); + mode.bind(token, Service); + mode.mock(token); + mode.final(token, { name: 'registered', read: () => 'value' }); + // @ts-expect-error The registered token fixes the supplied value's contract. + mode.final(token, { name: 1, read: () => 'value' }); // @ts-expect-error A class token fixes the required implementation contract. mode.bind(Service, Subject); // @ts-expect-error A class with a name cannot fall back to the registered named-token overload. @@ -61,7 +57,7 @@ for (const mode of [initial.expose(Service), initial]) { async function run() { const selected = await selective.compile(); const recursivelyComposed = await composed.compile(); - const selectedService: Mocked = selected.unitRef.get(Service); + const selectedService: Mocked = selected.unitRef.get('gateway'); const composedService: Mocked = recursivelyComposed.unitRef.get(Service); const registered: Mocked = selected.unitRef.get(token); registered.read.mockReturnValue('registered'); diff --git a/scripts/fixtures/release-type-compatibility/v5/helpers.ts b/scripts/fixtures/release-type-compatibility/v5/helpers.ts index b85f1ffd..1f8fcbff 100644 --- a/scripts/fixtures/release-type-compatibility/v5/helpers.ts +++ b/scripts/fixtures/release-type-compatibility/v5/helpers.ts @@ -24,6 +24,6 @@ export function composed() { return TestBed.sociable(Service).forbid('external'); } -export function selector() { +export function withMock() { return TestBed.sociable(Service).mock(Service); } diff --git a/scripts/fixtures/release-type-compatibility/v5/public-builder-types.ts b/scripts/fixtures/release-type-compatibility/v5/public-builder-types.ts index bab1cb14..9bb74c21 100644 --- a/scripts/fixtures/release-type-compatibility/v5/public-builder-types.ts +++ b/scripts/fixtures/release-type-compatibility/v5/public-builder-types.ts @@ -1,12 +1,14 @@ import type {} from '@suites/doubles.jest/unit'; import { TestBed, - type MockOverride, type SociableTestBedBuilder, type TestBedBuilder, type UnitTestBed, } from '@suites/unit'; +// @ts-expect-error v5 mock declarations return a configured builder. +import type { MockOverride } from '@suites/unit'; + class Service { name = 'service'; read(): string { @@ -28,26 +30,26 @@ const composedBase: TestBedBuilder = composed; initial.mock(Service); initial.compile(); -const configuredSelective = selective - .mock(Service) - .impl((stub) => ({ read: stub().mockReturnValue('selective') })); -const configuredComposed = composed.mock(Service).final({ read: () => 'composed' }); +const configuredSelective: SociableTestBedBuilder = selective.mock(Service); +const configuredComposed: SociableTestBedBuilder = composed.final(Service, { + name: 'composed', + read: () => 'value', +}); // @ts-expect-error Selective mode cannot transition to recursive composition. selective.compose(); -// @ts-expect-error Composed mode cannot transition to selective exposure. +// @ts-expect-error Configured composition cannot switch to selective exposure. configuredComposed.expose(Service); // @ts-expect-error Class-token inference preserves scalar property types. -selective.mock(Service).final({ name: 1 }); - -const override: MockOverride< - Service, - Subject, - SociableTestBedBuilder -> = selective.mock(Service); +selective.final(Service, { name: 1, read: () => 'value' }); +// @ts-expect-error The final value must supply the class's public members. +selective.final(Service, { read: () => 'value' }); +// @ts-expect-error Generated mocks are configured through unitRef after compilation. +configuredSelective.impl(() => ({})); async function run() { - const result: UnitTestBed = await override.final({ read: () => 'value' }).compile(); + const result: UnitTestBed = await configuredSelective.compile(); + result.unitRef.get(Service).read.mockReturnValue('selected'); result.unit.run(); // @ts-expect-error The subject retains its type. result.unit.missing(); From d96388fe0038c46cb865940958508c43cf6bcb3e Mon Sep 17 00:00:00 2001 From: omermorad Date: Sat, 28 Nov 2026 23:13:54 +0200 Subject: [PATCH 4/8] docs(unit): show mock configuration before and after construction --- JSDOC_STYLE_GUIDE.md | 3 +-- packages/core/README.md | 2 +- packages/di/inversify/README.md | 4 ++-- packages/di/nestjs/README.md | 2 +- packages/unit/README.md | 13 ++++++------- 5 files changed, 11 insertions(+), 13 deletions(-) diff --git a/JSDOC_STYLE_GUIDE.md b/JSDOC_STYLE_GUIDE.md index 076ec416..63b7b5b0 100644 --- a/JSDOC_STYLE_GUIDE.md +++ b/JSDOC_STYLE_GUIDE.md @@ -336,7 +336,6 @@ Error classes need special attention with comprehensive documentation: * // How to prevent/fix the error * await TestBed.solitary(MyService) * .mock(SomeDependency) - * .impl(() => ({ method: jest.fn() })) * .compile(); */ export class CustomError extends Error { @@ -454,8 +453,8 @@ export const stub = jest.fn(); * const { unit, unitRef } = await TestBed.sociable(MyService) * .expose(DependencyOne) * .mock(Logger) - * .impl(stub => ({ log: stub().mockReturnValue('overridden') })) * .compile(); + * unitRef.get(Logger).log.mockReturnValue('overridden'); */ ``` diff --git a/packages/core/README.md b/packages/core/README.md index d0bea58b..1fb61f39 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -45,7 +45,7 @@ Follow the [unit package README](https://github.com/suites-dev/unit/tree/master/ - Builds isolated tests with automatically mocked dependencies. - Keeps selected concrete dependencies real in sociable tests. - Resolves class, string, symbol, and adapter-registered identifiers. -- Applies `.impl()` mock implementations and `.final()` supplied values. +- Injects generated mocks for `.mock(token)` and caller-supplied values for `.final(token, value)`. - Preserves identifier identity and adapter metadata during lookups. Abstract classes are accepted as dependency tokens. The class under test and exposed dependencies must be concrete because Suites instantiates them. diff --git a/packages/di/inversify/README.md b/packages/di/inversify/README.md index 37425353..290e23da 100644 --- a/packages/di/inversify/README.md +++ b/packages/di/inversify/README.md @@ -129,13 +129,13 @@ Match named or tagged metadata in both overrides and lookups. For a dependency d ```typescript const { unitRef } = await TestBed.solitary(UserService) .mock(UserRepository, { named: 'primary' }) - .impl((stub) => ({ findName: stub().mockResolvedValue('Alice') })) .compile(); const users = unitRef.get(UserRepository, { named: 'primary' }); +users.findName.mockResolvedValue('Alice'); ``` -Suites builds a flat test container from class metadata. It does not consume production container bindings, run provider factories, or reproduce scopes and multi-binding collections. Supply explicit values or implementations through `.mock()` when needed. +Suites builds a flat test container from class metadata. It does not consume production container bindings, run provider factories, or reproduce scopes and multi-binding collections. Supply a ready value with `.final(UserRepository, value, { named: 'primary' })`. The examples use `.js` import paths for TypeScript ESM compatibility. When Jest transforms TypeScript source directly, configure its [relative import mapping](https://github.com/suites-dev/unit/tree/master/packages/doubles/jest#typescript-import-paths). diff --git a/packages/di/nestjs/README.md b/packages/di/nestjs/README.md index 36b30ec6..1460d15d 100644 --- a/packages/di/nestjs/README.md +++ b/packages/di/nestjs/README.md @@ -124,7 +124,7 @@ For Vitest, import `expect` and `it` from `vitest`. The repository is automatica For a custom token, use an explicit dependency type: `unitRef.get('USER_REPOSITORY')`. The `/metadata` reference rejects identifier metadata arguments, which NestJS does not use. -Suites builds a flat test container from the class. It does not load NestJS modules, run application lifecycle hooks, or reproduce production provider factories, scopes, and multi-provider configuration. Supply values with `.mock(token).final(value)` when needed. +Suites builds a flat test container from the class. It does not load NestJS modules, run application lifecycle hooks, or reproduce production provider factories, scopes, and multi-provider configuration. Supply values with `.final(token, value)` when needed. The examples use `.js` import paths for TypeScript ESM compatibility. When Jest transforms TypeScript source directly, configure its [relative import mapping](https://github.com/suites-dev/unit/tree/master/packages/doubles/jest#typescript-import-paths). diff --git a/packages/unit/README.md b/packages/unit/README.md index f579310d..5377b9d1 100644 --- a/packages/unit/README.md +++ b/packages/unit/README.md @@ -117,20 +117,18 @@ The examples use `.js` import paths for TypeScript ESM compatibility. When Jest ## Configure dependencies -Use `.impl()` to configure a generated mock, or `.final()` to inject a supplied value: +Use `.mock(Token)` to declare a generated mock. Configure it through `unitRef.get(Token)` before calling the method under test. If a constructor needs a configured dependency, supply it before compilation with `.final(Token, value)`. ```typescript const { unit, unitRef } = await TestBed.solitary(UserService) .mock(UserRepository) - .impl((stub) => ({ findName: stub().mockResolvedValue('Alice') })) .compile(); const users = unitRef.get(UserRepository); users.findName.mockResolvedValue('Bob'); const { unit: unitWithFake } = await TestBed.solitary(UserService) - .mock(UserRepository) - .final({ findName: async () => 'Alice' }) + .final(UserRepository, { findName: async () => 'Alice' }) .compile(); ``` @@ -138,14 +136,15 @@ A `.final()` dependency is injected as supplied and cannot be retrieved through ## Sociable tests -In v5, choose the real collaborators before configuring replacements. Replace v4's `.expose(A).expose(B)` with one `.expose(A, B)` call. Declare each collaborator your code uses that should be mocked. For example, this test keeps pricing real and gives inventory a controlled response. +In v5, sociable tests recursively construct known collaborators by default. To select the real collaborators explicitly, call `.expose()` before configuring replacements. Replace v4's `.expose(A).expose(B)` with one `.expose(A, B)` call. Declare each collaborator your code uses that should be mocked. For example, this test keeps pricing real and gives inventory a controlled response. ```typescript -const { unit } = await TestBed.sociable(Checkout) +const { unit, unitRef } = await TestBed.sociable(Checkout) .expose(Pricing) .mock(Inventory) - .impl((stub) => ({ available: stub().mockReturnValue(true) })) .compile(); + +unitRef.get(Inventory).available.mockReturnValue(true); ``` An undeclared dependency can be injected and left unused. Reading or calling it records a dependency violation and throws immediately. Configure your runner once so a caught violation also fails the run. From 04e5b63a16ccf6dcf1c1acf626af5d43d2551b03 Mon Sep 17 00:00:00 2001 From: omermorad Date: Sat, 28 Nov 2026 23:14:38 +0200 Subject: [PATCH 5/8] test(unit): supply complete final values for bound repositories --- e2e/jest/inversify/binding.e2e.test.ts | 2 +- e2e/jest/nestjs/binding.e2e.test.ts | 2 +- e2e/vitest/inversify/binding.e2e.test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/e2e/jest/inversify/binding.e2e.test.ts b/e2e/jest/inversify/binding.e2e.test.ts index 9941f63f..18e0065f 100644 --- a/e2e/jest/inversify/binding.e2e.test.ts +++ b/e2e/jest/inversify/binding.e2e.test.ts @@ -88,7 +88,7 @@ describe('v5 explicit token bindings', () => { expect(mocked.unit.primary.read()).toBe('live:value'); expect(() => mocked.unitRef.get(REPOSITORY)).toThrow(/exposed dependency/); - const supplied = { read: () => 'supplied replica' }; + const supplied = { leaf: new Leaf(), read: () => 'supplied replica' } satisfies Repository; const finalized = await bound.final(REPOSITORY, supplied, replica).compile(); expect(finalized.unit.replica).toBe(supplied); expect(finalized.unit.primary.read()).toBe('live:value'); diff --git a/e2e/jest/nestjs/binding.e2e.test.ts b/e2e/jest/nestjs/binding.e2e.test.ts index 50a58291..38204312 100644 --- a/e2e/jest/nestjs/binding.e2e.test.ts +++ b/e2e/jest/nestjs/binding.e2e.test.ts @@ -145,7 +145,7 @@ describe('v5 explicit token bindings', () => { /conflicting.*repository/i ); await expect( - bound.final(REPOSITORY, { read: () => 'supplied' }).compile() + bound.final(REPOSITORY, new Repository(new Leaf())).compile() ).rejects.toThrow(/conflicting.*repository/i); } expect(constructions).toBe(0); diff --git a/e2e/vitest/inversify/binding.e2e.test.ts b/e2e/vitest/inversify/binding.e2e.test.ts index 7218e554..0f1cea33 100644 --- a/e2e/vitest/inversify/binding.e2e.test.ts +++ b/e2e/vitest/inversify/binding.e2e.test.ts @@ -69,7 +69,7 @@ describe('v5 explicit token bindings', () => { expect(mocked.unit.primary.read()).toBe('live:value'); expect(() => mocked.unitRef.get(REPOSITORY)).toThrow(/exposed dependency/); - const supplied = { read: () => 'supplied replica' }; + const supplied = { leaf: new Leaf(), read: () => 'supplied replica' } satisfies Repository; const finalized = await bound.final(REPOSITORY, supplied, replica).compile(); expect(finalized.unit.replica).toBe(supplied); expect(finalized.unit.primary.read()).toBe('live:value'); From 09d09a0b831f8e9f09f3313d92cdc6c17860baba Mon Sep 17 00:00:00 2001 From: omermorad Date: Sat, 28 Nov 2026 23:16:13 +0200 Subject: [PATCH 6/8] feat(unit): configure generated mocks and ready values on the builder BREAKING CHANGE: Replace .mock(token).impl(factory) with .mock(token) and configure the generated mock through unitRef.get(token). Supply constructor-time behavior with .final(token, value) in place of .mock(token).final(value). The MockOverride interface has been removed. --- ...lder-empty-constructor.integration.test.ts | 6 +- ...ciable-testbed-builder.integration.test.ts | 17 +- ...litary-testbed-builder.integration.test.ts | 50 +-- packages/core/src/index.ts | 2 +- .../builders/sociable-unit-builder.ts | 82 +---- .../builders/solitary-unit-builder.ts | 68 ++-- .../src/services/builders/testbed-builder.ts | 333 ++++-------------- .../core/src/services/composition.spec.ts | 81 ++--- .../core/src/services/dependency-container.ts | 14 +- packages/core/src/services/unit-reference.ts | 8 +- packages/core/src/types.ts | 49 --- packages/doubles/jest/unit.d.ts | 63 +--- packages/doubles/vitest/unit.d.ts | 63 +--- packages/unit/src/index.ts | 2 +- packages/unit/src/testbed.ts | 1 - packages/unit/src/types.ts | 171 +-------- 16 files changed, 195 insertions(+), 815 deletions(-) diff --git a/packages/core/__test__/sociable-empty-constructor/sociable-testbed-builder-empty-constructor.integration.test.ts b/packages/core/__test__/sociable-empty-constructor/sociable-testbed-builder-empty-constructor.integration.test.ts index cbeb845e..eaca7a20 100644 --- a/packages/core/__test__/sociable-empty-constructor/sociable-testbed-builder-empty-constructor.integration.test.ts +++ b/packages/core/__test__/sociable-empty-constructor/sociable-testbed-builder-empty-constructor.integration.test.ts @@ -26,11 +26,7 @@ describe('Social TestBed Builder (Empty Constructor) Integration Tests', () => { loggerMock ); - const testBed = await unitBuilder - .expose(TestSociableService) - .mock(TestDependService) - .impl(() => ({})) - .compile(); + const testBed = await unitBuilder.expose(TestSociableService).mock(TestDependService).compile(); testServiceAsIfItWasUnderTest = testBed.unit; unitRef = testBed.unitRef; diff --git a/packages/core/__test__/sociable/sociable-testbed-builder.integration.test.ts b/packages/core/__test__/sociable/sociable-testbed-builder.integration.test.ts index 181602da..0441ef17 100644 --- a/packages/core/__test__/sociable/sociable-testbed-builder.integration.test.ts +++ b/packages/core/__test__/sociable/sociable-testbed-builder.integration.test.ts @@ -16,7 +16,6 @@ import { } from './assets/injectable-registry.fixture.js'; import type { UnitReference } from '../../src/index.js'; import { SociableTestBedBuilder, UnitMocker } from '../../src/index.js'; -import Mock = jest.Mock; describe('Social TestBed Builder Integration Tests', () => { let unitBuilder: SociableTestBedBuilder; @@ -40,15 +39,10 @@ describe('Social TestBed Builder Integration Tests', () => { .expose(UserApiService, UserDal, DatabaseService) .bind(DataMapper.token, DataMapper) .mock(UserVerificationService) - .impl(() => ({})) .mock(ApiService) - .impl(() => ({})) .mock('Repository') - .impl(() => ({})) .mock(TestLogger) - .impl((stubFn: Mock) => ({ log: stubFn().mockReturnValue('overridden') })) - .mock('SOME_VALUE_TOKEN') - .final(['some value']) + .final('SOME_VALUE_TOKEN', ['some value']) .compile(); userServiceAsIfItWasUnderTest = testBed.unit; @@ -59,7 +53,7 @@ describe('Social TestBed Builder Integration Tests', () => { expect(userServiceAsIfItWasUnderTest).toBeInstanceOf(UserService); }); - it('should log messages impl the overridden Logger.log method when UserService is initialized', () => { + it('records constructor calls on the generated logger', () => { const mockedLogger: StubbedInstance = unitRef.get(TestLogger); expect(mockedLogger.log).toHaveBeenNthCalledWith(1, 'Just logging a message'); @@ -139,22 +133,17 @@ describe('Social TestBed Builder Integration Tests', () => { }); it('rejects unused declarations when a mock cuts off their branch', async () => { - const configure = jest.fn(() => ({})); await expect( unitBuilder .expose(UserApiService, HttpClient) .mock(ApiService) - .impl(() => ({})) - .mock(TestLogger) - .final({ log: jest.fn() }) + .final(TestLogger, { log: jest.fn() }) .mock('absent') - .impl(configure) .compile() ).rejects.toMatchObject({ code: 'ER043', message: expect.stringMatching(/mock 'absent'.*exposure 'HttpClient'/), }); - expect(configure).not.toHaveBeenCalled(); expect(loggerMock.warn).not.toHaveBeenCalled(); }); }); diff --git a/packages/core/__test__/solitary/solitary-testbed-builder.integration.test.ts b/packages/core/__test__/solitary/solitary-testbed-builder.integration.test.ts index f49f3566..0938b9b8 100644 --- a/packages/core/__test__/solitary/solitary-testbed-builder.integration.test.ts +++ b/packages/core/__test__/solitary/solitary-testbed-builder.integration.test.ts @@ -41,25 +41,11 @@ describe('Solitary TestBed Builder Integration Test', () => { beforeAll(async () => { unitTestBed = await underTest .mock(ArbitraryClassTwo) - .impl(() => ({ - print: () => 'overridden', - })) .mock(ArbitraryClassFour) - .impl(() => ({ - print: () => 'overridden', - })) .mock('ANOTHER_TOKEN') - .impl(() => ({ - print: () => 'overridden', - })) .mock(symbolIdentifier, { key: 'value' }) - .impl(() => ({ - print: () => 'overridden', - })) - .mock('STRING_TOKEN') - .final('ARBITRARY_STRING') - .mock('TOKEN_WITH_UNDEFINED') - .final('SOME_VALUE') + .final('STRING_TOKEN', 'ARBITRARY_STRING') + .final('TOKEN_WITH_UNDEFINED', 'SOME_VALUE') .compile(); }); @@ -76,10 +62,8 @@ describe('Solitary TestBed Builder Integration Test', () => { ], [ArbitraryClassFour.name, undefined, MockedFromBuilder, ArbitraryClassFour], ['custom string-based token with function', undefined, MockedFromBuilder, 'ANOTHER_TOKEN'], - // ['custom token with undefined value', undefined, 'SOME_VALUE', 'TOKEN_WITH_UNDEFINED'], ['custom symbol-based token', { key: 'value' }, MockedFromBuilder, symbolIdentifier], [ArbitraryClassFive.name, undefined, MockedFromMocker, ArbitraryClassFive], - // ['custom token with constant value', undefined, 'ARBITRARY_STRING', 'STRING_TOKEN'], ])( 'should return a mock or a value for %p, with metadata %p mocked from %p', ( @@ -98,6 +82,29 @@ describe('Solitary TestBed Builder Integration Test', () => { expect(unitTestBed.unit).toBeInstanceOf(ClassUnderTest); }); + it('keeps sibling mock and final declarations isolated when compiling concurrently', async () => { + const ready = { print: () => 'ready' }; + const [original, mocked, finalized] = await Promise.all([ + underTest.compile(), + underTest.mock(ArbitraryClassTwo).compile(), + underTest.final(ArbitraryClassTwo, ready, { named: 'only' }).compile(), + ]); + + expect(original.unitRef.get(ArbitraryClassTwo)).toBe(MockedFromMocker); + expect(mocked.unitRef.get(ArbitraryClassTwo)).toBe(MockedFromBuilder); + expect(finalized.unit.getArguments()[1]).toBe(ready); + expect(finalized.unit.getArguments()[2]).toBe(ready); + expect(() => finalized.unitRef.get(ArbitraryClassTwo)).toThrow('faked dependency'); + }); + + it('injects a supplied undefined value before construction', async () => { + const compiled = await underTest + .final('TOKEN_WITH_UNDEFINED', undefined) + .compile(); + expect(compiled.unit.getArguments()[5]).toBeUndefined(); + expect(() => compiled.unitRef.get('TOKEN_WITH_UNDEFINED')).toThrow('faked dependency'); + }); + it('formats an unused qualified final without invoking token coercion or qualifier getters', async () => { const warn = jest.fn(); const builder = new SolitaryTestBedBuilder( @@ -117,17 +124,14 @@ describe('Solitary TestBed Builder Integration Test', () => { return coercion(); }, }; - await builder.mock(new OpaqueToken('unused'), metadata).final({}).compile(); + await builder.final(new OpaqueToken('unused'), {}, metadata).compile(); expect(warn).toHaveBeenCalledTimes(1); expect(warn).toHaveBeenCalledWith(expect.stringMatching(/WR001.*Unused final.*named/)); expect(coercion).not.toHaveBeenCalled(); }); it('should log a warning indicating the dependency was not found when mocking missing dependency', async () => { - await underTest - .mock('does-not-exists') - .impl(() => ({})) - .compile(); + await underTest.mock('does-not-exists').compile(); expect(loggerMock.warn).toHaveBeenCalledWith( expect.stringContaining("WR001): Unused mock override for 'does-not-exists'") diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 0e7e87c1..0bb227f4 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -5,5 +5,5 @@ export { type SociableTestBedBuilderState, } from './services/builders/sociable-unit-builder.js'; export type { UnitReference } from './services/unit-reference.js'; -export type { MockOverride, UnitTestBed } from './types.js'; +export type { UnitTestBed } from './types.js'; export type { TestBedBuilder } from './services/builders/testbed-builder.js'; diff --git a/packages/core/src/services/builders/sociable-unit-builder.ts b/packages/core/src/services/builders/sociable-unit-builder.ts index ee1c4c71..768c3430 100644 --- a/packages/core/src/services/builders/sociable-unit-builder.ts +++ b/packages/core/src/services/builders/sociable-unit-builder.ts @@ -1,9 +1,9 @@ import { isDeepStrictEqual } from 'node:util'; import { DependencyResolutionError, UnitErrorCode } from '@suites/types.common'; -import type { AbstractType, FinalValue, Type } from '@suites/types.common'; +import type { Type } from '@suites/types.common'; import type { DoublesAdapter, StubbedInstance } from '@suites/types.doubles'; import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; -import type { MockOverride, UnitTestBed } from '../../types.js'; +import type { UnitTestBed } from '../../types.js'; import type { IdentifierToFinal, IdentifierToMockOrFinal } from '../dependency-container.js'; import { normalizeIdentifier } from '../../normalize-identifier.static.js'; import { DependencyContainer } from '../dependency-container.js'; @@ -18,18 +18,20 @@ import { createGuardedDependency } from '../guarded-dependency.js'; import { UnitReference } from '../unit-reference.js'; import type { UnitMocker } from '../unit-mocker.js'; -type DependencyOf = - TIdentifier extends AbstractType - ? TDependency - : TIdentifier extends InjectableIdentifier - ? TDependency - : never; - -// A constructor's static properties can also match a registered structural token. -type NonClassIdentifier = Exclude, AbstractType> & - Partial>; +import { + InvalidBuilderArgument, + overrideMethods, + requireIdentifier, + type DependencyOf, + type NonClassIdentifier, + type Override, + type OverrideMethods, +} from './testbed-builder.js'; -interface ConfiguredBuilder> }> { +interface ConfiguredBuilder< + TClass, + TSelf extends { compile(): Promise> }, +> extends OverrideMethods { bind( identifier: TIdentifier, implementation: Type> @@ -38,10 +40,6 @@ interface ConfiguredBuilder, implementation: Type ): TSelf; - mock( - identifier: InjectableIdentifier, - ...qualifier: [] | [metadata: IdentifierMetadata | undefined] - ): MockOverride; compile(): Promise>; } @@ -74,17 +72,6 @@ type ConstructionMode = | { readonly kind: 'selective'; readonly classes: readonly Type[] } | { readonly kind: 'composed'; readonly forbidden: readonly InjectableIdentifier[] }; -type Override = ( - | { - readonly kind: 'mock'; - readonly create: (doubles: DoublesAdapter) => StubbedInstance; - } - | { readonly kind: 'final'; readonly value: FinalValue } -) & { - readonly identifier: InjectableIdentifier; - readonly metadata: IdentifierMetadata | undefined; -}; - interface SociableConfiguration { readonly overrides: readonly Override[]; readonly bindings: readonly { @@ -97,6 +84,7 @@ export class SociableTestBedBuilder { readonly #context: BuilderContext; public readonly bind: SociableTestBedBuilderState['bind']; public readonly mock: SociableTestBedBuilderState['mock']; + public readonly final: SociableTestBedBuilderState['final']; public readonly forbid: SociableTestBedBuilderState['forbid']; public readonly compile: SociableTestBedBuilderState['compile']; @@ -111,6 +99,7 @@ export class SociableTestBedBuilder { const composed = composedBuilder(this.#context, { overrides: [], bindings: [] }, []); this.bind = composed.bind; this.mock = composed.mock; + this.final = composed.final; this.forbid = composed.forbid; this.compile = composed.compile; } @@ -179,44 +168,11 @@ function configuredBuilder { - if (typeof implementation !== 'function') { - throw new InvalidBuilderArgument('An implemented mock requires a factory function.'); - } - return withOverride({ - kind: 'mock', - identifier, - metadata, - create: (doubles) => doubles.mock(implementation(doubles.stub)), - }); - }, - final: (value) => withOverride({ kind: 'final', identifier, metadata, value }), - }; - }, + ...overrideMethods(withOverride), compile: () => compile(context, configuration, mode), }; } -class InvalidBuilderArgument extends TypeError { - public readonly code = UnitErrorCode.INVALID_BUILDER_ARGUMENT; - public readonly severity = 'error'; - - public constructor(message: string) { - super( - `Invalid builder argument (code ${UnitErrorCode.INVALID_BUILDER_ARGUMENT})\n${message}` - ); - } -} - -function requireIdentifier(identifier: InjectableIdentifier, method: string): void { - if (identifier === null || identifier === undefined) { - throw new InvalidBuilderArgument(`.${method}() requires a dependency identifier.`); - } -} - // The construct trap tests the candidate's [[Construct]] without invoking consumer code. function isConstructor(value: unknown): boolean { if (typeof value !== 'function') return false; @@ -302,7 +258,7 @@ class SociableOverrides extends DependencyContainer { return final; } - const mock = this.mocks.get(match) ?? match.create(this.doubles); + const mock = this.mocks.get(match) ?? this.doubles.mock(); this.mocks.set(match, mock); const entry: IdentifierToMockOrFinal = [key, mock]; this.list().push(entry); diff --git a/packages/core/src/services/builders/solitary-unit-builder.ts b/packages/core/src/services/builders/solitary-unit-builder.ts index 867ff16f..e166b821 100644 --- a/packages/core/src/services/builders/solitary-unit-builder.ts +++ b/packages/core/src/services/builders/solitary-unit-builder.ts @@ -3,53 +3,59 @@ import { UnitWarningCode, type Type } from '@suites/types.common'; import { stringifyIdentifier } from '../functions.static.js'; import { UnitReference } from '../unit-reference.js'; import type { UnitMocker } from '../unit-mocker.js'; -import type { - IdentifierToMockOrFinal, - IdentifierToMockImplWithCb, -} from '../dependency-container.js'; -import { DependencyContainer } from '../dependency-container.js'; +import { DependencyContainer, type IdentifierToMockOrFinal } from '../dependency-container.js'; import type { UnitTestBed } from '../../types.js'; -import { TestBedBuilder } from './testbed-builder.js'; +import { overrideMethods, type Override, type TestBedBuilder } from './testbed-builder.js'; -export interface SolitaryTestBedBuilder extends TestBedBuilder {} +export class SolitaryTestBedBuilder implements TestBedBuilder { + public readonly mock: TestBedBuilder['mock']; + public readonly final: TestBedBuilder['final']; -export class SolitaryTestBedBuilder - extends TestBedBuilder - implements TestBedBuilder -{ public constructor( private readonly doublesAdapter: PromiseLike, private readonly unitMocker: UnitMocker, private readonly targetClass: Type, private readonly logger: Console ) { - super(); + const methods = overrideMethods((entry) => this.configured([entry])); + this.mock = methods.mock; + this.final = methods.final; } - public async compile(): Promise> { - const { mock: mockFn, stub: stubFn } = await this.doublesAdapter; + private configured(declarations: readonly Override[]): TestBedBuilder { + return { + ...overrideMethods((entry) => this.configured([...declarations, entry])), + compile: () => this.compileWith(declarations), + }; + } - const identifiersToMocksImpls: IdentifierToMockOrFinal[] = this.identifiersToBeMocked.map( - ([identifier, mockImplCallback]: IdentifierToMockImplWithCb) => { - return [identifier, mockFn(mockImplCallback(stubFn))]; - } - ); + public compile(): Promise> { + return this.compileWith([]); + } - const identifiersToFinal: IdentifierToMockOrFinal[] = this.identifiersToBeFinalized.map( - ([identifier, finalImpl]: IdentifierToMockOrFinal) => { - return [identifier, finalImpl]; + private async compileWith(declarations: readonly Override[]): Promise> { + const doubles = await this.doublesAdapter; + const mocks: IdentifierToMockOrFinal[] = []; + const finals: IdentifierToMockOrFinal[] = []; + for (const declaration of declarations) { + const { identifier, metadata } = declaration; + if (declaration.kind === 'mock') { + mocks.push([{ identifier, metadata }, doubles.mock()]); + } else { + finals.push([{ identifier, metadata }, declaration.value]); } - ); + } - const { container, instance, resolution } = await this.unitMocker.constructUnit( + const overrides = new DependencyContainer([...mocks, ...finals]); + const { container, instance, resolution } = await this.unitMocker.constructUnit( this.targetClass, [], - new DependencyContainer([...identifiersToMocksImpls, ...identifiersToFinal]) + overrides ); for (const entry of resolution.notFound) { const [{ identifier, metadata }] = entry; - const kind = identifiersToFinal.includes(entry) ? 'final' : 'mock'; + const kind = finals.includes(entry) ? 'final' : 'mock'; const dependency = stringifyIdentifier(identifier, metadata); const root = stringifyIdentifier(this.targetClass, undefined); this.logger.warn( @@ -57,9 +63,15 @@ export class SolitaryTestBedBuilder ); } + const finalizedTokens = new Set(finals.map(([key]) => key.identifier)); + const finalSites = container.list().filter(([{ identifier, metadata }]) => { + if (!finalizedTokens.has(identifier)) return false; + const override = overrides.resolveEntry(identifier, metadata); + return override !== undefined && finals.includes(override); + }); return { - unit: instance as TClass, - unitRef: new UnitReference(container, [], this.identifiersToBeFinalized), + unit: instance, + unitRef: new UnitReference(container, [], finalSites), }; } } diff --git a/packages/core/src/services/builders/testbed-builder.ts b/packages/core/src/services/builders/testbed-builder.ts index 0cf1b23c..e8f6b0ed 100644 --- a/packages/core/src/services/builders/testbed-builder.ts +++ b/packages/core/src/services/builders/testbed-builder.ts @@ -1,284 +1,79 @@ -import type { IdentifierToFinal, IdentifierToMockImplWithCb } from '../dependency-container.js'; -import type { DeepPartial, FinalValue, AbstractType } from '@suites/types.common'; +import type { AbstractType, FinalValue } from '@suites/types.common'; +import { UnitErrorCode } from '@suites/types.common'; import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; -import { normalizeIdentifier } from '../../normalize-identifier.static.js'; -import type { MockOverride, UnitTestBed } from '../../types.js'; -import type { ArgsType, Stub } from '@suites/types.doubles'; +import type { UnitTestBed } from '../../types.js'; -export abstract class TestBedBuilder implements TestBedBuilder { - protected readonly identifiersToBeMocked: IdentifierToMockImplWithCb[] = []; - protected readonly identifiersToBeFinalized: IdentifierToFinal[] = []; +export type DependencyOf = + TIdentifier extends AbstractType + ? TDependency + : TIdentifier extends InjectableIdentifier + ? TDependency + : never; - public mock(type: AbstractType): MockOverride; - public mock( - type: AbstractType, - identifierMetadata: IdentifierMetadata - ): MockOverride; - public mock(token: string): MockOverride; - public mock( - token: string, - identifierMetadata: IdentifierMetadata - ): MockOverride; - public mock(token: symbol): MockOverride; - public mock( - token: symbol, - identifierMetadata: IdentifierMetadata - ): MockOverride; - public mock( - identifier: InjectableIdentifier, - identifierMetadata?: IdentifierMetadata - ): MockOverride; - public mock( - identifier: InjectableIdentifier, - metadata?: IdentifierMetadata - ): MockOverride { - return { - impl: ( - mockImplementation: ( - stubFn: () => Stub> - ) => DeepPartial - ): TestBedBuilder => { - this.identifiersToBeMocked.push([ - normalizeIdentifier(identifier, metadata), - mockImplementation, - ]); - - return this; - }, - final: (finalImplementation: FinalValue): TestBedBuilder => { - this.identifiersToBeFinalized.push([ - normalizeIdentifier(identifier, metadata), - finalImplementation, - ]); +// Constructors can also satisfy an adapter's structurally registered token type. +export type NonClassIdentifier = Exclude, AbstractType> & + Partial>; - return this; - }, - }; - } - - /** - * Compiles the UnitTestBed instance. - * - * This method sets up and initializes the test environment for the specified class, - * resolving all dependencies and applying the defined mocks. The result is a - * `UnitTestBed` instance that provides access to the class under test and its - * mocked dependencies, ready for testing. - * - * @since 3.0.0 - * @returns A Promise that resolves to the compiled `UnitTestBed` instance. - * @template TClass The type of the class being tested. - * @example - * ```ts - * const unitTestBed = await testBedBuilder.compile(); - * const { unit, unitRef } = unitTestBed; - * // unit is the instance of the class under test - * // unitRef provides access to the mocked dependencies - * ``` - */ - public abstract compile(): Promise>; -} +type ReadyValue = unknown extends T + ? unknown + : T extends (...args: never[]) => unknown + ? T + : { [Key in keyof T]: T[Key] }; -/** - * Interface representing a builder for configuring and creating test beds for unit testing classes. - * - * @template TClass The type of the class being tested. - * @since 3.0.0 - */ -export interface TestBedBuilder { - /** - * Declares a dependency to be mocked using its type. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @param type - The type representing the dependency to be mocked. - * @template TClass The type of the class being tested. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock(MyService); - * ``` - */ - mock(type: AbstractType): MockOverride; +type Qualifier = [] | [metadata: IdentifierMetadata | undefined]; - /** - * Declares a dependency to be mocked using its type along with a corresponding metadata object. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @template TClass The type of the class being tested. - * @param type - The type representing the dependency to be mocked. - * @param identifierMetadata - Metadata object that corresponds to the type identifier. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock(MyService, metadata); - * ``` - */ +export interface OverrideMethods { + /** Inject a generated mock and retrieve it with unitRef.get() after compilation. */ mock( - type: AbstractType, - identifierMetadata: IdentifierMetadata - ): MockOverride; - - /** - * Declares a dependency to be mocked using a string-based token. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @template TClass The type of the class being tested. - * @param token - The string-based token representing the dependency to be mocked. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock('MyService'); - * ``` - */ - mock(token: string): MockOverride; + identifier: InjectableIdentifier, + ...qualifier: Qualifier + ): TBuilder; + /** Inject the supplied value by identity, including during construction. */ + final( + identifier: AbstractType | NonClassIdentifier, + value: ReadyValue, + ...qualifier: Qualifier + ): TBuilder; +} - /** - * Declares a dependency to be mocked using a string-based token along with a corresponding metadata object. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @template TClass The type of the class being tested. - * @param token - The string-based token representing the dependency to be mocked. - * @param identifierMetadata - Metadata object that corresponds to the string-based token. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock('MyService', metadata); - * ``` - */ - mock( - token: string, - identifierMetadata: IdentifierMetadata - ): MockOverride; +export interface TestBedBuilder extends OverrideMethods> { + compile(): Promise>; +} - /** - * Declares a dependency to be mocked using a symbol-based token. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @template TClass The type of the class being tested. - * @param token - The symbol-based token representing the dependency to be mocked. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock(MY_SERVICE_SYMBOL); - * ``` - */ - mock(token: symbol): MockOverride; +export type Override = { + readonly identifier: InjectableIdentifier; + readonly metadata: IdentifierMetadata | undefined; +} & ({ readonly kind: 'mock' } | { readonly kind: 'final'; readonly value: FinalValue }); - /** - * Declares a dependency to be mocked using a symbol-based token along with a corresponding metadata object. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @template TClass The type of the class being tested. - * @param token - The symbol-based token representing the dependency to be mocked. - * @param identifierMetadata - Metadata object that corresponds to the symbol-based token. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock(MY_SERVICE_SYMBOL, metadata); - * ``` - */ - mock( - token: symbol, - identifierMetadata: IdentifierMetadata - ): MockOverride; +export class InvalidBuilderArgument extends TypeError { + public readonly code = UnitErrorCode.INVALID_BUILDER_ARGUMENT; + public readonly severity = 'error'; - /** - * Declares a dependency to be mocked using its type, string-based token, or symbol-based token, - * with an optional metadata object. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @template TClass The type of the class being tested. - * @param identifier - The type or token representing the dependency to be mocked. - * @param identifierMetadata - Optional metadata object for the identifier. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock(MyService); - * // or - * const mockOverride = testBedBuilder.mock('MyService'); - * // or - * const mockOverride = testBedBuilder.mock(MY_SERVICE_SYMBOL, metadata); - * ``` - */ - mock( - identifier: InjectableIdentifier, - identifierMetadata?: IdentifierMetadata - ): MockOverride; + public constructor(message: string) { + super(`Invalid builder argument (code ${UnitErrorCode.INVALID_BUILDER_ARGUMENT})\n${message}`); + } } -/** - * Interface representing a builder for configuring and creating test beds for unit testing classes. - * - * @template TClass The type of the class being tested. - */ -export interface TestBedBuilder { - /** - * Declares a dependency to be mocked using its type. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @param type - The type representing the dependency to be mocked. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock(MyService); - * ``` - */ - mock(type: AbstractType): MockOverride; - - /** - * Declares a dependency to be mocked using a string-based token. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @param token - The string-based token representing the dependency to be mocked. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock('MyService'); - * ``` - */ - mock(token: string): MockOverride; - - /** - * Declares a dependency to be mocked using a symbol-based token. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @param token - The symbol-based token representing the dependency to be mocked. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock(MY_SERVICE_SYMBOL); - * ``` - */ - mock(token: symbol): MockOverride; +export function requireIdentifier(identifier: InjectableIdentifier, method: string): void { + if (identifier === null || identifier === undefined) { + throw new InvalidBuilderArgument(`.${method}() requires a dependency identifier.`); + } +} - /** - * Declares a dependency to be mocked using its type, string-based token, or symbol-based token. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being mocked. - * @param identifier - The type or token representing the dependency to be mocked. - * @param identifierMetadata - Optional metadata object for the identifier. - * @returns An instance of MockOverride for further configuration. - * @example - * ```ts - * const mockOverride = testBedBuilder.mock(MyService); - * // or - * const mockOverride = testBedBuilder.mock('MyService'); - * // or - * const mockOverride = testBedBuilder.mock(MY_SERVICE_SYMBOL, metadata); - * ``` - */ - mock( - identifier: InjectableIdentifier, - identifierMetadata?: IdentifierMetadata - ): MockOverride; +export function overrideMethods( + next: (entry: Override) => TBuilder +): OverrideMethods { + return { + mock(identifier, ...[metadata]) { + requireIdentifier(identifier, 'mock'); + return next({ kind: 'mock', identifier, metadata }); + }, + final(identifier: InjectableIdentifier, value: FinalValue, ...[metadata]: Qualifier) { + requireIdentifier(identifier, 'final'); + if (arguments.length < 2) { + throw new InvalidBuilderArgument('.final() requires an identifier and a value.'); + } + return next({ kind: 'final', identifier, metadata, value }); + }, + }; } diff --git a/packages/core/src/services/composition.spec.ts b/packages/core/src/services/composition.spec.ts index 55282603..e731c09f 100644 --- a/packages/core/src/services/composition.spec.ts +++ b/packages/core/src/services/composition.spec.ts @@ -381,7 +381,6 @@ describe('default sociable composition', () => { it('rejects token-wide overrides and bindings before constructing any collaborator', async () => { const token = Symbol('repository'); const constructed = jest.fn(); - const configureMock = jest.fn(() => ({})); class BoundRepository { constructor() { constructed(); @@ -400,17 +399,16 @@ describe('default sociable composition', () => { for (const mode of [selector.expose(BoundRepository), selector]) { const bound = mode.bind(token, BoundRepository); const declarations = [ - bound.mock(token).impl(configureMock), - bound.mock(token).final({}), - mode.mock(token).impl(configureMock).bind(token, BoundRepository), - mode.mock(token).final({}).bind(token, BoundRepository), + bound.mock(token), + bound.final(token, {}), + mode.mock(token).bind(token, BoundRepository), + mode.final(token, {}).bind(token, BoundRepository), ]; for (const declaration of declarations) { await expect(declaration.compile()).rejects.toThrow(/conflicting.*repository/i); } } expect(constructed).not.toHaveBeenCalled(); - expect(configureMock).not.toHaveBeenCalled(); }); it('rejects contradictory bindings in both construction modes', async () => { @@ -470,8 +468,8 @@ describe('default sociable composition', () => { it('keeps independently configured branches of one composed builder isolated', async () => { const composed = builder(); - const one = composed.mock(Client).final({ read: () => 'one' }); - const two = composed.mock(Client).impl(() => ({ read: () => 'two' })); + const one = composed.final(Client, { read: () => 'one' }); + const two = composed.mock(Client); const [original, first, second] = await Promise.all([ composed.compile(), @@ -480,23 +478,24 @@ describe('default sociable composition', () => { ]); expect(original.unit.repository.client.read()).toBe('live'); expect(first.unit.repository.client.read()).toBe('one'); - expect(second.unit.repository.client.read()).toBe('two'); + expect(second.unit.repository.client).toBe(second.unitRef.get(Client)); + expect(second.unit.repository.client).not.toBe(first.unit.repository.client); }); it('rejects duplicate overrides for the same identifier and qualifier in both modes', async () => { for (const selected of [builder().expose(Repository), builder()]) { - const mock = jest.fn(() => ({ read: () => 'implemented' })); - const firstMock = selected.mock(Client).impl(mock); - const firstFinal = selected.mock(Client).final({ read: () => 'final' }); + const firstMock = selected.mock(Client); + const firstFinal = selected.final(Client, { read: () => 'final' }); for (const first of [firstMock, firstFinal]) { - await expect(first.mock(Client).impl(mock).compile()).rejects.toMatchObject({ - code: 'ER042', - }); - await expect(first.mock(Client).final({}).compile()).rejects.toMatchObject({ + await expect(first.mock(Client).compile()).rejects.toMatchObject({ code: 'ER042', }); + await expect(first.final(Client, { read: () => 'second' }).compile()).rejects.toMatchObject( + { + code: 'ER042', + } + ); } - expect(mock).not.toHaveBeenCalled(); } }); @@ -512,18 +511,14 @@ describe('default sociable composition', () => { registry([[Root, [parameter(Client, primary), parameter(Client, secondary)]]]) ); const fallback = { read: () => 'fallback' }; - for (const mode of [selector.expose(Client), selector.mock(Client).final(fallback)]) { - const { unit, unitRef } = await mode - .mock(Client, secondary) - .impl(() => ({ read: () => 'secondary' })) - .compile(); + for (const mode of [selector.expose(Client), selector.final(Client, fallback)]) { + const { unit, unitRef } = await mode.mock(Client, secondary).compile(); expect(unit.second).toBe(unitRef.get(Client, secondary)); - expect(unit.second.read()).toBe('secondary'); expect(() => unitRef.get(Client, primary)).toThrow(); } }); - it('materializes a shared mock once per compile and preserves exceptions from its factory', async () => { + it('shares an explicit mock across matching requests within each compilation', async () => { class Root { constructor( readonly first: Client, @@ -534,36 +529,22 @@ describe('default sociable composition', () => { Root, registry([[Root, [parameter(Client, primary), parameter(Client, secondary)]]]) ); - const create = jest.fn(() => ({ read: () => 'test' })); - const configured = selector.mock(Client).impl(create); + const configured = selector.mock(Client); const first = await configured.compile(); const second = await configured.compile(); expect(first.unit.first).toBe(first.unit.second); expect(first.unit.first).not.toBe(second.unit.first); - expect(create).toHaveBeenCalledTimes(2); - const failure = new TypeError('application callback failed'); - await expect( - selector - .mock(Client) - .impl(() => { - throw failure; - }) - .compile() - ).rejects.toBe(failure); + expect(first.unitRef.get(Client, primary)).toBe(first.unit.first); }); it('retains composed mode through both override forms', async () => { - const implemented = await builder() - .mock(Client) - .impl(() => ({ read: () => 'implemented' })) - .compile(); + const implemented = await builder().mock(Client).compile(); const finalized = await builder() - .mock(Client) - .final({ read: () => 'final' }) + .final(Client, { read: () => 'final' }) .compile(); expect(implemented.unit.repository).toBeInstanceOf(Repository); - expect(implemented.unit.repository.client.read()).toBe('implemented'); + expect(implemented.unit.repository.client).toBe(implemented.unitRef.get(Client)); expect(finalized.unit.repository).toBeInstanceOf(Repository); expect(finalized.unit.repository.client.read()).toBe('final'); }); @@ -633,7 +614,7 @@ describe('default sociable composition', () => { it('keeps forbidden boundaries on the branch that declares them', async () => { const composed = builder(); const forbidden = composed.forbid(Client); - const mocked = composed.mock(Client).final({ read: () => 'replacement' }); + const mocked = composed.final(Client, { read: () => 'replacement' }); const [original, blocked, replaced] = await Promise.all([ composed.compile(), forbidden.compile(), @@ -662,20 +643,14 @@ describe('default sociable composition', () => { }); it('rejects conflicting mock and final declarations at compile time', async () => { - const mocked = builder() - .forbid(Client) - .mock(Client) - .impl(() => ({ read: () => 'mocked' })) - .compile(); + const mocked = builder().forbid(Client).mock(Client).compile(); const finalized = builder() .forbid(Client) - .mock(Client) - .final({ read: () => 'final' }) + .final(Client, { read: () => 'final' }) .compile(); const qualified = builder() .forbid(Client) - .mock(Client, primary) - .final({ read: () => 'qualified' }) + .final(Client, { read: () => 'qualified' }, primary) .compile(); for (const compilation of [mocked, finalized, qualified]) { diff --git a/packages/core/src/services/dependency-container.ts b/packages/core/src/services/dependency-container.ts index a9943c76..1e4b3579 100644 --- a/packages/core/src/services/dependency-container.ts +++ b/packages/core/src/services/dependency-container.ts @@ -1,23 +1,15 @@ import type { normalizeIdentifier } from '../normalize-identifier.static.js'; import { isDeepStrictEqual } from 'node:util'; import type { ClassInjectable, IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; -import type { Stub, StubbedInstance } from '@suites/types.doubles'; -import type { ConstantValue, DeepPartial, FinalValue } from '@suites/types.common'; +import type { StubbedInstance } from '@suites/types.doubles'; +import type { ConstantValue, FinalValue } from '@suites/types.common'; export type IdentifierToMockOrFinal = [ Pick & { readonly metadata?: IdentifierMetadata }, StubbedInstance | FinalValue, ]; -export type IdentifierToFinal = [ - ReturnType, - FinalValue, -]; - -export type IdentifierToMockImplWithCb = [ - Pick & { readonly metadata?: IdentifierMetadata }, - (stubFn: () => Stub) => DeepPartial, -]; +export type IdentifierToFinal = [ReturnType, FinalValue]; export interface DependencyContainer { resolve( diff --git a/packages/core/src/services/unit-reference.ts b/packages/core/src/services/unit-reference.ts index 603f84af..33087d11 100644 --- a/packages/core/src/services/unit-reference.ts +++ b/packages/core/src/services/unit-reference.ts @@ -4,11 +4,7 @@ import type { StubbedInstance } from '@suites/types.doubles'; import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; import type { AbstractType } from '@suites/types.common'; import { DependencyResolutionError } from '@suites/types.common'; -import type { - DependencyContainer, - IdentifierToFinal, - IdentifierToMockOrFinal, -} from './dependency-container.js'; +import type { DependencyContainer, IdentifierToMockOrFinal } from './dependency-container.js'; import { stringifyIdentifier } from './functions.static.js'; /** @@ -148,7 +144,7 @@ export class UnitReference { public constructor( private readonly mocksContainer: DependencyContainer, private readonly exposedInstances: readonly InjectableIdentifier[], - private readonly fakedDependencies: IdentifierToFinal[], + private readonly fakedDependencies: readonly IdentifierToMockOrFinal[], private readonly composedDependencies: readonly IdentifierToMockOrFinal[0][] = [], private readonly exposedDependencies: readonly IdentifierToMockOrFinal[0][] = [] ) {} diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index a1985c10..f2f64fee 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -1,7 +1,4 @@ -import type { DeepPartial } from '@suites/types.common'; -import type { ArgsType, Stub } from '@suites/types.doubles'; import type { UnitReference } from './services/unit-reference.js'; -import type { TestBedBuilder } from './services/builders/testbed-builder.js'; /** * Represents the testing environment for a specific class, encapsulating both the instance @@ -45,49 +42,3 @@ export interface UnitTestBed { */ unitRef: UnitReference; } - -/** - * Provides methods to define overrides for mocking dependencies within the testing environment. - * This interface allows setting up specific behaviors or responses from the mocked dependencies, - * facilitating precise and controlled testing scenarios. - * - * @template TDependency The type of the dependency being mocked. This generic ensures that - * the mocks are appropriately typed, enhancing the development experience with type safety. - * @template TClass The type of the class under test. This provides context to the TestBedBuilder, - * linking the mock setups directly with the class being tested. - * @since 3.0.0 - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - */ -export interface MockOverride< - TDependency, - TClass, - TBuilder extends Pick, 'compile'> = TestBedBuilder, -> { - /** - * Configures mocks with stubs that can be retrieved and modified later via `unitRef.get()`. - * - * Use this when you need to change mock behavior after TestBed compilation. - * - * @since 3.0.0 - * @param mockImplementation - A function that receives a stub function and returns a partial - * implementation of the dependency. - * @returns A TestBedBuilder instance for method chaining. - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - */ - impl( - mockImplementation: (stubFn: Stub>) => DeepPartial - ): TBuilder; - - /** - * Sets immutable final values for a mocked dependency. The mock cannot be retrieved - * or modified after compilation. - * - * Use this for token-injected configuration objects or when you don't need runtime modification. - * - * @since 3.0.0 - * @param finalImplementation - The final implementation for the dependency. - * @returns A TestBedBuilder instance for method chaining. - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - */ - final(finalImplementation: DeepPartial): TBuilder; -} diff --git a/packages/doubles/jest/unit.d.ts b/packages/doubles/jest/unit.d.ts index 87c7307c..2c8bba3d 100644 --- a/packages/doubles/jest/unit.d.ts +++ b/packages/doubles/jest/unit.d.ts @@ -1,9 +1,7 @@ /// -import type { DeepPartial, AbstractType } from '@suites/types.common'; +import type { AbstractType } from '@suites/types.common'; import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; -import type { TestBedBuilder } from '@suites/core.unit'; import type { Mocked as JestMocked, Stub as JestStub } from '.'; -import type { ArgsType } from '@suites/types.doubles'; declare module '@suites/unit' { /** @@ -170,63 +168,4 @@ declare module '@suites/core.unit' { identifierMetadata?: IdentifierMetadata ): JestMocked; } - - /** - * Interface to define overrides for mocking dependencies in a test environment. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @template TDependency The type of the dependency to be mocked. - * @template TClass The type of the class under test. - */ - export interface MockOverride< - TDependency, - TClass, - TBuilder extends Pick, 'compile'> = TestBedBuilder, - > { - /** - * Provides a mock implementation using stub functions for methods. - * - * Use this when you need fine-grained control over method behavior with stub functions. - * The stub function is automatically provided for creating mocked methods. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @since 3.0.0 - * @param mockImplementation - Function that receives a stub creator and returns the mock - * @returns A TestBedBuilder instance for chaining - * - * @example - * ```ts - * await TestBed.solitary(MyService) - * .mock(Logger) - * .impl((stub) => ({ log: stub().mockReturnValue(undefined) })) - * .compile(); - * ``` - */ - impl( - mockImplementation: ( - stubFn: () => JestStub> - ) => DeepPartial - ): TBuilder; - - /** - * Provides a final implementation with concrete values or functions. - * - * Use this when you want to directly provide the mock implementation without stubs, - * useful for simple mocks or when providing constant values. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @since 3.0.0 - * @param finalImplementation - The mock implementation object - * @returns A TestBedBuilder instance for chaining - * - * @example - * ```ts - * await TestBed.solitary(MyService) - * .mock('CONFIG') - * .final({ apiUrl: 'http://test.api', timeout: 5000 }) - * .compile(); - * ``` - */ - final(finalImplementation: DeepPartial): TBuilder; - } } diff --git a/packages/doubles/vitest/unit.d.ts b/packages/doubles/vitest/unit.d.ts index 76579449..ca0f5a3b 100644 --- a/packages/doubles/vitest/unit.d.ts +++ b/packages/doubles/vitest/unit.d.ts @@ -1,9 +1,7 @@ /// -import type { DeepPartial, AbstractType } from '@suites/types.common'; +import type { AbstractType } from '@suites/types.common'; import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; -import type { TestBedBuilder } from '@suites/core.unit'; import type { Mocked as VitestMocked, Stub as VitestStub } from '.'; -import type { ArgsType } from '@suites/types.doubles'; declare module '@suites/unit' { /** @@ -170,63 +168,4 @@ declare module '@suites/core.unit' { identifierMetadata?: IdentifierMetadata ): VitestMocked; } - - /** - * Interface to define overrides for mocking dependencies in a test environment. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @template TDependency The type of the dependency to be mocked. - * @template TClass The type of the class under test. - */ - export interface MockOverride< - TDependency, - TClass, - TBuilder extends Pick, 'compile'> = TestBedBuilder, - > { - /** - * Provides a mock implementation using stub functions for methods. - * - * Use this when you need fine-grained control over method behavior with stub functions. - * The stub function is automatically provided for creating mocked methods. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @since 3.0.0 - * @param mockImplementation - Function that receives a stub creator and returns the mock - * @returns A TestBedBuilder instance for chaining - * - * @example - * ```ts - * await TestBed.solitary(MyService) - * .mock(Logger) - * .impl((stub) => ({ log: stub().mockReturnValue(undefined) })) - * .compile(); - * ``` - */ - impl( - mockImplementation: ( - stubFn: () => VitestStub> - ) => DeepPartial - ): TBuilder; - - /** - * Provides a final implementation with concrete values or functions. - * - * Use this when you want to directly provide the mock implementation without stubs, - * useful for simple mocks or when providing constant values. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @since 3.0.0 - * @param finalImplementation - The mock implementation object - * @returns A TestBedBuilder instance for chaining - * - * @example - * ```ts - * await TestBed.solitary(MyService) - * .mock('CONFIG') - * .final({ apiUrl: 'http://test.api', timeout: 5000 }) - * .compile(); - * ``` - */ - final(finalImplementation: DeepPartial): TBuilder; - } } diff --git a/packages/unit/src/index.ts b/packages/unit/src/index.ts index 43bf6078..341197d0 100644 --- a/packages/unit/src/index.ts +++ b/packages/unit/src/index.ts @@ -5,4 +5,4 @@ export type { SolitaryTestBedBuilder, SociableTestBedBuilder, } from './types.js'; -export type { UnitReference, MockOverride } from '@suites/core.unit'; +export type { UnitReference } from '@suites/core.unit'; diff --git a/packages/unit/src/testbed.ts b/packages/unit/src/testbed.ts index 05e5159a..83bcb872 100644 --- a/packages/unit/src/testbed.ts +++ b/packages/unit/src/testbed.ts @@ -80,7 +80,6 @@ export class TestBed { * const { unit, unitRef } = await TestBed.sociable(OrderService) * .expose(PriceCalculator) * .mock(InventoryService) - * .impl((stub) => ({ checkStock: stub() })) * .compile(); * * // Configure mocked dependencies diff --git a/packages/unit/src/types.ts b/packages/unit/src/types.ts index e82c17ae..3fe7696c 100644 --- a/packages/unit/src/types.ts +++ b/packages/unit/src/types.ts @@ -1,11 +1,10 @@ import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; -import type { DeepPartial, Type, AbstractType } from '@suites/types.common'; -import type { ArgsType, Stub, StubbedInstance } from '@suites/types.doubles'; +import type { Type, AbstractType } from '@suites/types.common'; +import type { StubbedInstance } from '@suites/types.doubles'; import type { TestBedBuilder as TestBedBuilderCore, SociableTestBedBuilderState, UnitReference as UnitReferenceCore, - MockOverride as MockOverrideCore, } from '@suites/core.unit'; /** @@ -264,167 +263,5 @@ export interface UnitTestBed { unitRef: UnitReference; } -/** - * Interface to define overrides for mocking dependencies in a test environment. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @template TDependency The type of the dependency to be mocked. - * @template TClass The type of the class under test. - */ -export interface MockOverride< - TDependency, - TClass, - TBuilder extends Pick, 'compile'> = TestBedBuilder, -> extends MockOverrideCore { - /** - * Provides a mock implementation using stub functions for methods. - * - * Use this when you need fine-grained control over method behavior with stub functions. - * The stub function is automatically provided for creating mocked methods. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @since 3.0.0 - * @param mockImplementation - Function that receives a stub creator and returns the mock - * @returns A TestBedBuilder instance for chaining - * - * @example - * ```ts - * await TestBed.solitary(MyService) - * .mock(Logger) - * .impl((stub) => ({ log: stub().mockReturnValue(undefined) })) - * .compile(); - * ``` - */ - impl( - mockImplementation: (stubFn: Stub>) => DeepPartial - ): TBuilder; - - /** - * Provides a final implementation with concrete values or functions. - * - * Use this when you want to directly provide the mock implementation without stubs, - * useful for simple mocks or when providing constant values. - * - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - * @since 3.0.0 - * @param finalImplementation - The mock implementation object - * @returns A TestBedBuilder instance for chaining - * - * @example - * ```ts - * await TestBed.solitary(MyService) - * .mock('CONFIG') - * .final({ apiUrl: 'http://test.api', timeout: 5000 }) - * .compile(); - * ``` - */ - final(finalImplementation: DeepPartial): TBuilder; -} - -/** - * Provides methods to configure and finalize the `TestBed`. - * - * @template TClass The class type being tested. - * @since 3.0.0 - * @see {@link https://suites.dev/docs/api-reference/mock-configuration | Mock Configuration} - */ -export interface TestBedBuilder { - /** - * Declares a dependency to be mocked using its type. - * - * @since 3.0.0 - * @param type - The type of the dependency. - * @template TDependency The type of the dependency being mocked. - * @returns An instance of MockOverride for further configuration. - */ - mock(type: AbstractType): MockOverride; - - /** - * Declares a dependency to be mocked using its type along with a corresponding metadata object. - * - * @since 3.0.0 - * @param type - The type of the dependency. - * @param identifierMetadata - the identifier metadata. - * @template TDependency The type of the dependency being mocked. - * @returns An instance of MockOverride for further configuration. - */ - mock( - type: AbstractType, - identifierMetadata: IdentifierMetadata - ): MockOverride; - - /** - * Declares a dependency to be mocked using a string-based token. - * - * @since 3.0.0 - * @param token - The token string representing the dependency to be mocked. - * @template TDependency The type of the dependency being mocked. - * @returns An instance of MockOverride for further configuration. - */ - mock(token: string): MockOverride; - - /** - * Declares a dependency to be mocked using a string-based token along with a corresponding - * metadata object. - * - * @since 3.0.0 - * @param token - The token string representing the dependency to be mocked. - * @param identifierMetadata - the identifier metadata. - * @template TDependency The type of the dependency being mocked. - * @returns An instance of MockOverride for further configuration. - */ - mock( - token: string, - identifierMetadata: IdentifierMetadata - ): MockOverride; - - /** - * Declares a dependency to be mocked using a symbol-based token. - * - * @since 3.0.0 - * @param token - The token symbol representing the dependency to be mocked. - * @template TDependency The type of the dependency being mocked. - * @returns An instance of MockOverride for further configuration. - */ - mock(token: symbol): MockOverride; - - /** - * Declares a dependency to be mocked using a symbol-based token along with a corresponding - * metadata object. - * - * @since 3.0.0 - * @param token - The token symbol representing the dependency to be mocked. - * @param identifierMetadata - the identifier metadata if exists. - * @template TDependency The type of the dependency being mocked. - * @returns An instance of MockOverride for further configuration. - */ - mock( - token: symbol, - identifierMetadata: IdentifierMetadata - ): MockOverride; - - /** - * Declares a dependency to be mocked using a flexible identifier. - * - * @since 3.0.0 - * @param identifier - The identifier representing the dependency. It can be of type - * `AbstractType`, `string`, or `symbol`. - * @param identifierMetadata - the identifier metadata if exists. - * @template TDependency The type of the dependency being mocked. - * @returns An instance of MockOverride for further configuration. - */ - mock( - identifier: InjectableIdentifier, - identifierMetadata?: IdentifierMetadata - ): MockOverride; - /** - * Finalizes the test environment configuration and builds the test instance. - * - * This method completes the builder chain and returns the configured test environment - * with the unit under test and references to all mocked dependencies. - * - * @since 3.0.0 - * @returns A Promise resolving to UnitTestBed with unit and unitRef - */ - compile(): Promise>; -} +/** Configures dependency replacements before compiling a unit. */ +export interface TestBedBuilder extends TestBedBuilderCore {} From 657084accb0d7f43ea2aeddedae4ebea8ab21339 Mon Sep 17 00:00:00 2001 From: omermorad Date: Sat, 28 Nov 2026 23:17:53 +0200 Subject: [PATCH 7/8] fix(core): preserve the types of supplied dependency values --- packages/core/src/services/builders/testbed-builder.ts | 6 +++--- packages/core/src/services/dependency-container.ts | 6 +++--- packages/core/src/services/dependency-map.ts | 9 ++------- packages/core/src/services/dependency-resolver.ts | 10 +++++----- 4 files changed, 13 insertions(+), 18 deletions(-) diff --git a/packages/core/src/services/builders/testbed-builder.ts b/packages/core/src/services/builders/testbed-builder.ts index e8f6b0ed..3f876d34 100644 --- a/packages/core/src/services/builders/testbed-builder.ts +++ b/packages/core/src/services/builders/testbed-builder.ts @@ -1,4 +1,4 @@ -import type { AbstractType, FinalValue } from '@suites/types.common'; +import type { AbstractType } from '@suites/types.common'; import { UnitErrorCode } from '@suites/types.common'; import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; import type { UnitTestBed } from '../../types.js'; @@ -43,7 +43,7 @@ export interface TestBedBuilder extends OverrideMethods( requireIdentifier(identifier, 'mock'); return next({ kind: 'mock', identifier, metadata }); }, - final(identifier: InjectableIdentifier, value: FinalValue, ...[metadata]: Qualifier) { + final(identifier: InjectableIdentifier, value: unknown, ...[metadata]: Qualifier) { requireIdentifier(identifier, 'final'); if (arguments.length < 2) { throw new InvalidBuilderArgument('.final() requires an identifier and a value.'); diff --git a/packages/core/src/services/dependency-container.ts b/packages/core/src/services/dependency-container.ts index 1e4b3579..6e7c1519 100644 --- a/packages/core/src/services/dependency-container.ts +++ b/packages/core/src/services/dependency-container.ts @@ -2,14 +2,14 @@ import type { normalizeIdentifier } from '../normalize-identifier.static.js'; import { isDeepStrictEqual } from 'node:util'; import type { ClassInjectable, IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; import type { StubbedInstance } from '@suites/types.doubles'; -import type { ConstantValue, FinalValue } from '@suites/types.common'; +import type { ConstantValue } from '@suites/types.common'; export type IdentifierToMockOrFinal = [ Pick & { readonly metadata?: IdentifierMetadata }, - StubbedInstance | FinalValue, + unknown, ]; -export type IdentifierToFinal = [ReturnType, FinalValue]; +export type IdentifierToFinal = [ReturnType, unknown]; export interface DependencyContainer { resolve( diff --git a/packages/core/src/services/dependency-map.ts b/packages/core/src/services/dependency-map.ts index 6f5e8a1f..4f421a2e 100644 --- a/packages/core/src/services/dependency-map.ts +++ b/packages/core/src/services/dependency-map.ts @@ -1,7 +1,5 @@ import { isDeepStrictEqual } from 'node:util'; import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; -import type { FinalValue, Type } from '@suites/types.common'; -import type { StubbedInstance } from '@suites/types.doubles'; import type { IdentifierToMockOrFinal } from './dependency-container.js'; export class DependencyMap { @@ -15,16 +13,13 @@ export class DependencyMap { public set( identifier: InjectableIdentifier, - value: Type | StubbedInstance | FinalValue, + value: unknown, metadata?: IdentifierMetadata ): void { this.resolvedDependencies.push([{ identifier, metadata }, value]); } - public get( - identifier: InjectableIdentifier, - metadata?: IdentifierMetadata - ): Type | StubbedInstance | FinalValue | undefined { + public get(identifier: InjectableIdentifier, metadata?: IdentifierMetadata): unknown { return this.resolvedDependencies.find( ([key]) => key.identifier === identifier && isDeepStrictEqual(key.metadata, metadata) )?.[1]; diff --git a/packages/core/src/services/dependency-resolver.ts b/packages/core/src/services/dependency-resolver.ts index 65d1fbc1..c50c662a 100644 --- a/packages/core/src/services/dependency-resolver.ts +++ b/packages/core/src/services/dependency-resolver.ts @@ -1,8 +1,8 @@ import { isDeepStrictEqual } from 'node:util'; import { DependencyResolutionError, SuitesError, UnitErrorCode } from '@suites/types.common'; import { stringifyIdentifier } from './functions.static.js'; -import type { AbstractType, FinalValue, Type } from '@suites/types.common'; -import type { MockFunction, StubbedInstance } from '@suites/types.doubles'; +import type { AbstractType, Type } from '@suites/types.common'; +import type { MockFunction } from '@suites/types.doubles'; import type { ClassInjectable, DependencyInjectionAdapter, @@ -27,7 +27,7 @@ export type ResolverOptions = readonly boundaries: CompositionBoundaryLookup; }; -type ResolvedDependency = Type | FinalValue | StubbedInstance; +type ResolvedDependency = IdentifierToMockOrFinal[1]; type ResolvedBoundary = { value: ResolvedDependency }; function validFailure(result: InspectionResult, target: Type): result is InspectionFailure { @@ -175,7 +175,7 @@ export class DependencyResolver { metadata?: IdentifierMetadata ): ResolvedDependency { if (this.dependencyMap.has(identifier, metadata)) { - return this.dependencyMap.get(identifier, metadata) as ResolvedDependency; + return this.dependencyMap.get(identifier, metadata); } const boundary = this.resolveBoundary(identifier, metadata); @@ -223,7 +223,7 @@ export class DependencyResolver { identifier: InjectableIdentifier = type ): ResolvedDependency { if (this.dependencyMap.has(identifier, metadata)) { - return this.dependencyMap.get(identifier, metadata) as ResolvedDependency; + return this.dependencyMap.get(identifier, metadata); } const tracksCycles = this.options.mode !== 'solitary'; From 9fe33d6a27ee242fd5c32cab1e99c9a3e12ca3be Mon Sep 17 00:00:00 2001 From: omermorad Date: Sat, 28 Nov 2026 23:19:01 +0200 Subject: [PATCH 8/8] fix(unit): retain adapter mock types on explicitly typed test beds --- packages/unit/src/types.ts | 118 +------------------------------------ 1 file changed, 2 insertions(+), 116 deletions(-) diff --git a/packages/unit/src/types.ts b/packages/unit/src/types.ts index 3fe7696c..88a204ea 100644 --- a/packages/unit/src/types.ts +++ b/packages/unit/src/types.ts @@ -1,5 +1,4 @@ -import type { IdentifierMetadata, InjectableIdentifier } from '@suites/types.di'; -import type { Type, AbstractType } from '@suites/types.common'; +import type { Type } from '@suites/types.common'; import type { StubbedInstance } from '@suites/types.doubles'; import type { TestBedBuilder as TestBedBuilderCore, @@ -63,120 +62,7 @@ export interface SolitaryTestBedBuilder extends TestBedBuilder { * expect(mockLogger.log).toHaveBeenCalled(); * ``` */ -export interface UnitReference extends UnitReferenceCore { - /** - * Retrieves a reference to the mocked object of a dependency corresponding to its type identifier. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being retrieved. - * @param type - The type representing the dependency. - * @throws {@link DependencyResolutionError} If the dependency is not found. - * @returns The mocked object corresponding to the provided type identifier. - */ - get(type: AbstractType): StubbedInstance; - - /** - * Retrieves a reference to the mocked object of a dependency corresponding to its type identifier - * and metadata object. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being retrieved. - * @param type - The type representing the dependency. - * @param identifierMetadata - A metadata object that corresponds to the type identifier. - * @throws {@link DependencyResolutionError} If the dependency is not found. - * @returns The mocked object corresponding to the provided - * symbol-based token. - */ - get( - type: AbstractType, - identifierMetadata: IdentifierMetadata - ): StubbedInstance; - - /** - * Retrieves a reference to the mocked object of a dependency corresponding to a string-based token. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being retrieved. - * @param token - The string-based token representing the dependency. - * @throws {@link DependencyResolutionError} If the dependency is not found. - * @returns The mocked object corresponding to the provided string-based token. - */ - get(token: string): StubbedInstance; - - /** - * Retrieves a reference to the mocked object of a dependency corresponding to a string-based - * token and an identifier metadata object. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being retrieved. - * @param token - The symbol-based token representing the dependency. - * @param identifierMetadata - An accompanying metadata object for the token identifier. - * @throws {@link DependencyResolutionError} If the dependency is not found. - * @returns The mocked object corresponding to the provided - * symbol-based token. - */ - get( - token: string, - identifierMetadata: IdentifierMetadata - ): StubbedInstance; - - /** - * Retrieves a reference to the mocked object of a dependency corresponding to a symbol-based token. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being retrieved. - * @param token - The symbol-based token representing the dependency. - * @throws {@link DependencyResolutionError} If the dependency is not found. - * @returns The mocked object corresponding to the provided symbol-based token. - */ - get(token: symbol): StubbedInstance; - - /** - * Retrieves a reference to the mocked object of a dependency corresponding to a symbol-based - * token and an identifier metadata object. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being retrieved. - * @param token - The symbol-based token representing the dependency. - * @param identifierMetadata - An accompanying metadata object for the token identifier. - * @throws {@link DependencyResolutionError} If the dependency is not found. - * @returns The mocked object corresponding to the provided symbol-based token. - */ - get( - token: symbol, - identifierMetadata: IdentifierMetadata - ): StubbedInstance; - - /** - * Retrieves a mocked dependency by its type, string, or symbol token with optional metadata. - * - * This method provides flexibility in retrieving dependencies by allowing various identifier types. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being retrieved. - * @param identifier - The token representing the dependency. It can be of type `AbstractType`, `string`, or `symbol`. - * @param identifierMetadata - A corresponding metadata object for the token identifier. - * @throws {@link DependencyResolutionError} If the dependency is not found. - * @returns The mocked instance corresponding to the provided identifier and metadata. - */ - get( - identifier: InjectableIdentifier, - identifierMetadata?: IdentifierMetadata - ): StubbedInstance; - - /** - * Retrieves a mocked dependency by its type, string, or symbol token. - * - * This method provides flexibility in retrieving dependencies by allowing various identifier types. - * - * @since 3.0.0 - * @template TDependency The type of the dependency being retrieved. - * @param identifier - The token representing the dependency. It can be of type `AbstractType`, `string`, or `symbol`. - * @throws {@link DependencyResolutionError} If the dependency is not found. - * @returns The mocked instance corresponding to the provided identifier. - */ - get(identifier: InjectableIdentifier): StubbedInstance; -} +export interface UnitReference extends UnitReferenceCore {} /** * A factory interface for creating UnitTestBed instances for testing classes.