TestBed.solitary()
Create isolated unit tests with all dependencies mocked
Creates a test environment where all dependencies are automatically mocked for testing a class in complete isolation.
Signature
TestBed.solitary<T>(targetClass: Type<T>): SolitaryTestBedBuilder<T>Parameters
| Parameter | Type | Description |
|---|---|---|
targetClass | Type<T> | The class constructor to test in isolation |
Returns
Returns a SolitaryTestBedBuilder<TClass> instance with methods for configuring the test environment:
.mock(dependency)- Configure specific mock behavior before compilation.compile()- Finalizes configuration and creates the test environment
Description
TestBed.solitary() creates a test environment where all of the class’s dependencies are mocked by default. This is ideal for testing the internal logic of a class in complete isolation.
Suites automatically identifies and mocks all constructor dependencies, which can then be accessed via unitRef.get(). Learn more in the Virtual Test Container guide.
Configuring Mocks
See Mock Configuration for details on .mock().final() and .mock().impl().
Examples
Basic Usage
// All dependencies of UserService are auto-mockedconst { unit, unitRef } = await TestBed.solitary(UserService).compile();
// Retrieve and configure mocks as needed for a testconst userRepository = unitRef.get(UserRepository);userRepository.findById.mockResolvedValue(testUser);Token Injections
// Class with token-injected dependencies@Injectable()class PaymentService { constructor( @Inject('CONNECTION') private connection: Connection, @Inject('API_KEY') private apiKey: string ) {}}
const { unitRef } = await TestBed.solitary(PaymentService).compile();
// Retrieve mocks by tokenconst database = unitRef.get<Connection>('CONNECTION');const apiKey = unitRef.get<string>('API_KEY');Type Safety
All retrieved mocks are fully type-safe, providing autocompletion and compile-time checks.
const repository = unitRef.get(UserRepository);
// ✅ TypeScript knows all methodsrepository.findById.mockResolvedValue(user);
// ❌ Compile error: method doesn't existrepository.invalidMethod.mockReturnValue(123);See Also
- Solitary Tests Guide - Conceptual guide
- TestBed.sociable() - Test with real dependencies
- UnitReference - Accessing mocked dependencies with
unitRef.get() - Virtual Test Container - How Suites auto-mocks dependencies