Charter
Problem. Unit-testing an @injectable class from @codefast/di by hand means a
bind(...).toConstantValue(...) for every collaborator, and a unit built outside a container skips the lifecycle hooks
production runs.
Goals.
- Mock every dependency a class declares, discovered through di's own
MetadataReader. - Build the unit through a real container, so
@postConstruct, accessor injection and@preDestroyrun as in production. - Keep chosen collaborators real while the rest stay mocked.
- Work with any test framework's spies, with no test-framework dependency, and type every mock with that backend's own surface.
Non-goals.
- Integration testing: a sociable bed is a unit test over a small real subtree.
A suite states its mock backend once
Status: Accepted
Context. A mock must be typed as the spy that built it, without an adapter package or module augmentation, and a default backend nobody chose would hand a suite mocks its matchers do not understand.
Decision. createTestBed({ mockFactory }) returns the entry point every bed in a suite begins from, and the
factory's return type flows through every bed it begins. mockFactory is required; the TestBed export is the entry
point on the built-in spy, and createTestBed() without a factory throws MissingMockFactoryError where the compiler
cannot stop it.
Consequences. With () => vi.fn(), mocks.get(token).send carries Vitest's own mock surface. A bed has no backend
but its entry point's, so a mock is never typed as one backend and built from another.
Tokens are the boundary, classes can be exposed
Status: Accepted
Context. A unit test needs a clear line between the logic under test and the outside world.
Decision. A Token-keyed dependency is always mocked, in both modes. A class-keyed dependency stays real only when
a sociable bed exposes it, and its own dependencies follow the same rules recursively.
Consequences. A token-keyed dependency can be stubbed or given a value with .using(), but never exposed; exposing
the unit itself, or a class the unit never reaches, is an ExposureError.
A value the test supplies is sealed
Status: Accepted
Context. A value bound with .using(), .usingAll() or .absent(), and an exposed class, has no mock surface, and
the test already holds the reference it passed in.
Decision. mocks.get returns only auto-mocks and .stub stubs; for anything else it throws SealedDependencyError
rather than hand the value back typed as a mock.
Consequences. A Mocked<T> from mocks.get always has the backend's surface it is typed with.
TestingError mirrors DiError without extending it
Status: Accepted
Context. A test-setup failure and a resolution failure call for different handling.
Decision. Every error extends TestingError, which carries a stable code like di's DiError but does not extend
it.
Consequences. A caller can catch setup failures separately from resolution failures.
License
Released under the MIT License.