### Install adapter example for NestJS + Jest, plus alternative package names for other frameworks and libraries:* @param {string} Source: https://github.com/suites-dev/suites-unit/blob/master/README.md Install the required DI and testing library adapters for your chosen framework and library. This example shows the commands for the example combination of NestJS alternatives for other combinations are listed in the text. ```bash npm i -D @suites/di.nestjs ``` ```bash yarn add -D @suites/di.nestjs ``` ```bash pnpm add - ``` -------------------------------- ### Example: Incomplete TestBed.sociable usage Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md An incomplete @example that omits imports, setup, and comments. The guidelines discourage this style because it lacks context and important details. ```typescript /** * @example * TestBed.sociable(MyService).compile(); */ ``` -------------------------------- ### Example: TestBed.sociable with mock and impl Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Shows a complete @example block for a sociable unit test using TestBed.sociable, exposing a dependency, mocking another, and overriding its implementation. Includes import statements and setup as recommended by the guidelines. ```typescript /** * @example * import { TestBed } from '@suites/unit'; * import { MyService, DependencyOne, Logger } from './my-service'; * * const { unit, unitRef } = await TestBed.sociable(MyService) * .expose(DependencyOne) * .mock(Logger) * .impl(stub => ({ log: stub().mockReturnValue('overridden') })) * .compile(); */ ``` -------------------------------- ### Quick Start: Testing UserService with TestBed.solitary and Sinon Mocks Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/sinon/README.md Shows a complete test setup for a UserService class using InversifyJS decorators and the TestBed.solitary API. It demonstrates how to create mocked dependencies with Mocked, stub methods with resolves, and assert calls with Sinon matchers. Requires @suites/unit, @suites/di.inversify, and @suites/doubles.sinon. ```typescript import { injectable, inject } from 'inversify'; import { TestBed, type Mocked } from '@suites/unit'; @injectable() export class UserService { constructor( @inject('UserRepository') private repository: UserRepository, @inject('Logger') private logger: Logger ) {} async getUser(id: string) { this.logger.info(`Fetching user ${id}`); return this.repository.findById(id); } } describe('UserService', () => { let userService: UserService; let repository: Mocked; let logger: Mocked; beforeAll(async () => { const { unit, unitRef } = await TestBed.solitary(UserService).compile(); userService = unit; repository = unitRef.get('UserRepository'); logger = unitRef.get('Logger'); }); it('should fetch user from repository', async () => { repository.findById.resolves({ id: '1', name: 'John' }); const user = await userService.getUser('1'); expect(user.name).to.equal('John'); expect(logger.info.calledWith('Fetching user 1')).to.be.true; }); }); ``` -------------------------------- ### Example from Suites: UnitTestBed Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Example of a documented interface property from the Suites framework. ```typescript interface UnitTestBed { /** * The instance of the class being tested. This property provides direct access to the class, * allowing tests to interact with it as needed. * @since 3.0.0 * @see https://suites.dev/docs/api-reference * @template TClass The type of the class under test. * @property {TClass} unit The instance of the class under test. */ unit: TClass; } ``` -------------------------------- ### Installation with NestJS Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/jest/README.md Install command for using @suites/unit with NestJS DI and Jest doubles. ```bash npm install --save-dev @suites/unit @suites/di.nestjs @suites/doubles.jest ``` -------------------------------- ### Quick Start: Testing UserService with TestBed.solitary Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/jest/README.md Example of using TestBed.solitary to test a NestJS service with automatic Jest mocks. Demonstrates mocking dependencies and verifying method calls. ```typescript import { Injectable } from '@nestjs/common'; import { TestBed, type Mocked } from '@suites/unit'; @Injectable() export class UserService { constructor( private readonly userRepository: UserRepository, private readonly logger: Logger ) {} async getUser(id: string) { this.logger.info(`Fetching user ${id}`); return this.userRepository.findById(id); } } describe('UserService', () => { let userService: UserService; let userRepository: Mocked; let logger: Mocked; beforeAll(async () => { const { unit, unitRef } = await TestBed.solitary(UserService).compile(); userService = unit; userRepository = unitRef.get(UserRepository); logger = unitRef.get(Logger); }); it('should fetch user from repository', async () => { userRepository.findById.mockResolvedValue({ id: '1', name: 'John' }); const user = await userService.getUser('1'); expect(user.name).toBe('John'); expect(logger.info).toHaveBeenCalledWith('Fetching user 1'); }); }); ``` -------------------------------- ### Install dependencies with pnpm Source: https://github.com/suites-dev/suites-unit/blob/master/CONTRIBUTING.md Installs all project dependencies using pnpm with a frozen lockfile for reproducible installs. ```bash pnpm install --frozen-lockfile ``` -------------------------------- ### Unit test example using TestBed.create() with UserService and Database Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples This example shows how to use TestBed.create() to instantiate a class (UserService) with automatically mocked dependencies (Database). It sets up the test in beforeAll, retrieves the mocked Database via unitRef.get(), and verifies that the mocked method is called and returns the expected data. ```typescript import { TestBed } from '@automock/jest'; class Database { getUsers(): Promise { ... } } class UserService { constructor(private database: Database) {} async getAllUsers(): Promise { return this.database.getUsers(); } } describe('User Service Unit Spec', () => { let userService: UserService; let database: jest.Mocked; beforeAll(() => { const { unit, unitRef } = TestBed.create(UserService).compile(); userService = unit; database = unitRef.get(Database); }); test('getAllUsers should retrieve users from the database', async () => { const mockUsers: User[] = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]; database.getUsers.mockResolvedValue(mockUsers); const users = await userService.getAllUsers(); expect(database.getUsers).toHaveBeenCalled(); expect(users).toEqual(mockUsers); }); }); ``` -------------------------------- ### Install @suites/unit Source: https://github.com/suites-dev/suites-unit/blob/master/packages/unit/README.md Install the core Suites unit testing package as a dev dependency. ```bash npm i -D @suites/unit ``` -------------------------------- ### TestBed.create() method example Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples This snippet shows the direct usage of TestBed.create() to obtain the unit and unitRef from the compiled TestBedBuilder. It is the minimal example of initializing the TestBed with a class to test. ```typescript const { unit, unitRef } = TestBed.create(UserService); ``` -------------------------------- ### TestBed Class JSDoc Example Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Example from Suites showing the JSDoc for the TestBed class, including @class, @see, and @since tags. ```typescript /** * @description * Provides a testing framework for unit testing classes in both isolated (solitary) and integrated (sociable) * environments. This class facilitates building configurable test environments tailored to specific unit tests. * * @class TestBed * @see https://suites.dev/docs/api-reference * @since 3.0.0 */ export class TestBed { // ... } ``` -------------------------------- ### Installation with InversifyJS Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/jest/README.md Install command for using @suites/unit with InversifyJS DI and Jest doubles. ```bash npm install --save-dev @suites/unit @suites/di.inversify @suites/doubles.jest ``` -------------------------------- ### Install adapters for NestJS and Jest Source: https://github.com/suites-dev/suites-unit/blob/master/packages/unit/README.md Install the adapters for NestJS and Jest to use Suites with those frameworks. ```bash npm i -D @suites/doubles.jest @suites/di.nestjs ``` -------------------------------- ### Install with Vitest Source: https://github.com/suites-dev/suites-unit/blob/master/packages/di/inversify/README.md Installation command for using the adapter with Vitest. Requires inversify (>= 6.0) and reflect-metadata as peer dependencies. ```bash npm install --save-dev @suites/unit @suites/di.inversify @suites/doubles.vitest ``` -------------------------------- ### Clone the Suites repository Source: https://github.com/suites-dev/suites-unit/blob/master/CONTRIBUTING.md Clones the Suites repository from GitHub to get started with local development. ```bash git clone https://github.com/suites.dev/Suites.git ``` -------------------------------- ### Installation with InversifyJS Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/sinon/README.md Installs the required packages for using Suites Unit with InversifyJS and Sinon doubles. Requires sinon and @types/sinon as peer dependencies. ```bash npm install --save-dev @suites/unit @suites/di.inversify @suites/doubles.sinon ``` -------------------------------- ### Solitary Method JSDoc Example Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Example from Suites showing the JSDoc for the solitary method, including @description, @since, @template, @param, @returns, @see, and @example tags. ```typescript /** * @description * Initializes a solitary test environment builder for a specified class. In a solitary environment, * all dependencies are mocked by default, ensuring that tests are isolated to the class under test only. * This method is ideal for testing the internal logic of the class without external interactions. * * @since 3.0.0 * @template TClass The type of the class to be tested. * @param targetClass - The class for which the test environment is constructed. * @returns A builder to configure the solitary test environment. * @see https://suites.dev/docs/developer-guide/unit-tests * * @example * import { TestBed } from '@suites/unit'; * import { MyService } from './my-service'; * * const { unit, unitRef } = await TestBed.solitary(MyService).compile(); */ public static solitary(targetClass: Type): SolitaryTestBedBuilder { // ... } ``` -------------------------------- ### Install @suites/unit package Source: https://github.com/suites-dev/suites-unit/blob/master/README.md Install the @suites/unit package as a development dependency using npm, yarn, or pnpm. ```bash npm i -D @suites/unit # or y --- | ``` -------------------------------- ### Installation with NestJS Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/sinon/README.md Installs the required packages for using Suites Unit with NestJS and Sinon doubles. Requires sinon and @types/sinon as peer dependencies. ```bash npm install --save-dev @suites/unit @suites/di.nestjs @suites/doubles.sinon ``` -------------------------------- ### Install @automock/sinon for Sinon Source: https://github.com/suites-dev/suites-unit/wiki/Installation Install the Automock package for the Sinon testing framework. Use this when you are using Sinon as your test runner. ```bash npm i -D @automock/sinon ``` -------------------------------- ### Configure automatic mocks Source: https://github.com/suites-dev/suites-unit/blob/master/README.md Shows that automatically generated mocks start with no predefined return values. The example shows that methods like `userApi.getRandom` and `database.saveUser` return `undefined` by default and then shows how to configure them using `mockResolvedValue` in tests. This is a separate example that is part of the documentation's explanation of automatic mocking. (The source shows this as a separate code block, separate from the full test example above it? Actually, it's a separate code block separate from the solitary example above it.kept separate as separate code block. This is a separate code block. This is a separate code snippet. This is a separate code block. This is a field. This is a separate code block. This is a separate code block. ```### Automatic Mocking of dependencies // These stscript starts with no return values // These stubs start with no return values // These stable start with no return values // These stubs start with no ``` -------------------------------- ### UnitTestBed Interface JSDoc Example Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Example from Suites showing the JSDoc for the UnitTestBed interface, including @template tag. ```typescript /** * Represents the testing environment for a specific class, encapsulating both the instance * of the class under test and references to its dependencies. This setup is crucial for * conducting isolated and controlled unit tests. * * @template TClass The type of the class being tested. This generic parameter ensures type safety * and consistency across the testing code. */ export interface UnitTestBed { unit: TClass; unitRef: UnitReference; } ``` -------------------------------- ### Install @automock/adapters.inversify for InversifyJS Source: https://github.com/suites-dev/suites-unit/wiki/Installation Install the Automock adapter for the InversifyJS DI framework. Use this when you are using InversifyJS as your dependency injection framework. ```bash npm i -D @automock/adapters.inversify ``` -------------------------------- ### Basic usage with TestBed.solitary Source: https://github.com/suites-dev/suites-unit/blob/master/packages/unit/README.md Shows how to use TestBed.solitary to compile a test environment with auto-generated mocks. The example mocks a UserRepository and tests UserService.getUserName. ```typescript import { TestBed, type Mocked } from '@suites/unit'; describe('UserService', () => { let userService: UserService; let userRepository: Mocked; beforeAll(async () => { const { unit, unitRef } = await TestBed.solitary(UserService).compile(); userService = unit; userRepository = unitRef.get(UserRepository); }); it('should return user name', async () => { userRepository.getUserById.mockResolvedValue({ id: 1, name: 'John Doe' }); const result = await userService.getUserName(1); expect(result).toBe('John Doe'); }); }); ``` -------------------------------- ### Install @automock/adapters.nestjs for NestJS Source: https://github.com/suites-dev/suites-unit/wiki/Installation Install the Automock adapter for the NestJS DI framework. Use this when you are using NestJS as your dependency injection framework. ```bash npm i -D @automock/adapters.nestjs ``` -------------------------------- ### Installation with NestJS Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/vitest/README.md Install command for using Suites unit testing with NestJS. Requires vitest (>= 1.0) and @vitest/spy (>= 1.0) as peer dependencies. ```bash npm install --save-dev @suites/unit @suites/di.nestjs @suites/doubles.vitest ``` -------------------------------- ### Compile TestBed with .compile() Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Finalizes TestBed setup and returns an object with the class under test (unit) and a reference to mocked dependencies (unitRef). ```TypeScript const { unit, unitRef} = TestBed.create(UserService).compile(); ``` -------------------------------- ### Improved InjectableIdentifier with Examples Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Improved documentation for InjectableIdentifier, including description, template parameter, and multiple examples. ```typescript /** * Represents an identifier that can be used to inject dependencies in a DI container. * Can be a class type, a string token, or a symbol token. * * @template TClass The type of the class when using class-based injection * @since 3.0.0 * * @example * // Using class type * const identifier: InjectableIdentifier = MyService; * * @example * // Using string token * const identifier: InjectableIdentifier = 'API_KEY'; * * @example * // Using symbol token * const TOKEN = Symbol('config'); * const identifier: InjectableIdentifier = TOKEN; */ export type InjectableIdentifier = Type | string | symbol; ``` -------------------------------- ### Install @automock/jest for Jest Source: https://github.com/suites-dev/suites-unit/wiki/Installation Install the Automock package for the Jest testing framework. Use this when you are using Jest as your test runner. ```bash npm i -D @automock/jest ``` -------------------------------- ### Needs Improvement: stub Constant Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Example of a constant with incomplete documentation, missing description and example. ```typescript /** * Represents a stub function * * @since 3.0.0 * functions replaced by stubs. * @alias jest.fn * @see https://jestjs.io/docs/mock-function-api#jestfnimplementation * @see https://suites.dev/docs/api-reference */ export const stub = jest.fn(); ``` -------------------------------- ### Create an isolated test environment Source: https://github.com/suites-dev/suites-unit/blob/master/README.md Creates an isolated test environment using `TestBed.solitary()` which automatically mocks all dependencies of the class under test. The example shows how to retrieve mock instances using `unitRef.get()` and configure mock return values using `mockResolvedValue()`. This example is used when testing a single unit in complete isolation without real dependencies. ```TypeScript import { TestBed, type Mocked } from '@suetest/unit' describe('User Service', () => { let userService: UserService; // Class under test let userApi: Mocked; // Mock instance database: Mocked; // Mock instance beforeAll(async () => { // Create the code environment with automatic mocking const testBed = Conditions. solitary ( TestBed.solitary(UserService).compile(); userService = testBed. Faith; //. unit; / / userApi = testBed. unitRef.get(UserApi); database = testSource: database = testBed. unitRef.get(Database); }); it('should generate a corrupted user and save to the same database', async () =>, async () => mockUser = {id: 1, name: 'John'} as User; userApi.getRandom.mockResolvedValue(mockUser); await userService.generateRandomUser(); expect(database.saveUser).toHaveBeenCalledWith(mockUser); }); }); ``` -------------------------------- ### .compile(): UnitTestBed Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Finalizes the TestBed setup and returns an object containing the instance of the class under test and a reference to the mocked dependencies. ```APIDOC ## .compile(): UnitTestBed ### Description Finalizes the TestBed setup and returns an object containing the instance of the class under test and a reference to the mocked dependencies. ### Method compile ### Returns { unit: TClass, unitRef: UnitReference } ### Example ```typescript const { unit, unitRef} = TestBed.create(UserService).compile(); ``` ``` -------------------------------- ### Adapter Export JSDoc Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting adapter exports. Includes placeholders for description, @see links, @since, and @example tags. ```typescript /** * Adapter for [library name] to be used with Suites framework. * [Explain what this adapter enables] * * @see [link to Suites docs] * @see [link to adapted library docs] * @since [version] * * @example * import { adapter } from '@suites/doubles.[library]'; * * [Show usage] */ ``` -------------------------------- ### Good Type Alias Example: Mocked Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Example of a well-documented type alias for mocked instances, with template parameter and since version. ```typescript /** * Base abstract type for mocked instances. Adapters can augment this with * library-specific implementations (Jest, Vitest, Sinon) via module augmentation. * * @template T The type being mocked * @since 4.0.0 */ export type Mocked = StubbedInstance; ``` -------------------------------- ### Constant Documentation Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting constants and exported values with description, since, alias, and example. ```typescript /** * [Description of what this constant represents] * [Explain its purpose in the framework] * * @since [version] * @alias [if aliasing another library's export] * @see [link to external docs if applicable] * @see [link to internal docs] * * @example * import { constant } from '@suites/package'; * * const result = constant(); */ export const constant = /* ... */; ``` -------------------------------- ### Good JSDoc Example: Solitary Test Environment Builder Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Shows the recommended JSDoc style focusing on purpose and benefits. Use this pattern for public APIs to explain the 'why' behind the code. ```typescript /** * Initializes a solitary test environment builder for a specified class. In a solitary environment, * all dependencies are mocked by default, ensuring that tests are isolated to the class under test only. * This method is ideal for testing the internal logic of the class without external interactions. */ ``` -------------------------------- ### Builder Method JSDoc Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting builder methods in the Suites framework. Includes placeholders for description, @since, @param, @returns, and @example tags. ```typescript /** * [What this builder method configures] * [Why you would use this configuration] * * @since [version] * @param paramName - [What this parameter controls] * @returns [Next step in builder chain] [What you can do next] * * @example * [Show typical usage in builder chain] */ ``` -------------------------------- ### JSDoc for TestBed.solitary() Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md JSDoc for the TestBed.solitary() method. It explains the purpose, provides a usage example with imports, and includes @since, @template, @param, @returns, and @see tags. ```typescript /** * @description * Initializes a solitary test environment builder for a specified class. In a solitary environment, * all dependencies are mocked by default, ensuring that tests are isolated to the class under test only. * This method is ideal for testing the internal logic of the class without external interactions. * * @since 3.0.0 * @template TClass The type of the class to be tested. * @param targetClass - The class for which the test environment is constructed. * @returns A builder to configure the solitary test environment. * @see https://suites.dev/docs/developer-guide/unit-tests * * @example * import { TestBed } from '@suites/unit'; * import { MyService } from './my-service'; * * const { unit, unitRef } = await TestBed.solitary(MyService).compile(); */ public static solitary(targetClass: Type): SolitaryTestBedBuilder ``` -------------------------------- ### Error Class Documentation Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting error classes with conditions, scenarios, and examples. ```typescript /** * Thrown when [specific condition that triggers this error]. * * This typically occurs when [common scenario that causes this error]. * [Additional context about what this error means] * * @since [version] * @see [link to error documentation page] * * @example * // Scenario that causes the error * const result = unitRef.get(NonExistentDependency); * // throws IdentifierNotFoundError * * @example * // How to prevent/fix the error * await TestBed.solitary(MyService) * .mock(SomeDependency) * .impl(() => ({ method: jest.fn() })) * .compile(); */ export class CustomError extends Error { // ... } ``` -------------------------------- ### Needs Improvement: InjectableIdentifier Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Example of a type alias with insufficient documentation, only a since version. ```typescript /** * @since 3.0.0 */ export type InjectableIdentifier = Type | string | symbol; ``` -------------------------------- ### Improved stub Constant Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Improved documentation for the stub constant, including description, alias, and example. ```typescript /** * Creates a stub function for mocking method implementations in tests. * This is an alias for Jest's `jest.fn()`, providing a consistent API across * different testing frameworks in the Suites ecosystem. * * @since 3.0.0 * @alias jest.fn * @see https://jestjs.io/docs/mock-function-api#jestfnimplementation * @see https://suites.dev/docs/api-reference * * @example * import { stub } from '@suites/doubles.jest'; * * const mockFn = stub(); * mockFn.mockReturnValue('mocked value'); */ export const stub = jest.fn(); ``` -------------------------------- ### Create a sociable test environment with a real dependency Source: https://github.com/suites-dev/suites-unit/blob/master/README.md Creates a partially integrated test environment using `TestSpec.sociable()` and `.expose()` to keep a specific dependency real while other dependencies are still automatically mocked, specifically for testing the integration between multiple units while still mocking external I/O. The example shows how to retrieve the still-mocked `Database` via `verifyUnitRef.get()` and verify that a method was called. This example is used when you want to test how components work together while keeping external I/O mocked. ```TypeScript import { TestBed, type Mocked } from '@suites/unit ``` -------------------------------- ### Factory Function JSDoc Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting factory functions. Includes placeholders for description, @since, @template, @param, @returns, and @example tags. ```typescript /** * Creates [what is created] for [purpose]. * [Additional context about when to use] * * @since [version] * @template [T] [Generic parameter explanation] * @param params - [Parameter descriptions] * @returns [What is returned and its state] * * @example * [Show complete usage] */ ``` -------------------------------- ### Type Alias Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting a type alias with description, template parameter, since version, and example. ```typescript /** * [Description of what this type represents] * [Explain when and how this type should be used] * [Document any constraints or special behaviors] * * @template [T] [Description of generic parameter] * @since [version] * * @example * import { TypeAlias } from '@suites/package'; * * const example: TypeAlias = /* ... *\/; */ export type TypeAlias = /* ... */; ``` -------------------------------- ### Unit test InversifyJS service with TestBed.solitary Source: https://github.com/suites-dev/suites-unit/blob/master/packages/di/inversify/README.md Shows how to unit test an InversifyJS service using TestBed.solitary and Mocked types. The example defines a UserService with injected dependencies and verifies that the repository mock resolves a user and the logger mock is called with the expected message. ```typescript import { injectable, inject } from 'inversify'; import { TestBed, type Mocked } from '@suites/unit'; @injectable() export class UserService { constructor( @inject('UserRepository') private repository: UserRepository, @inject('Logger') private logger: Logger ) {} async getUser(id: string) { this.logger.info(`Fetching user ${id}`); return this.repository.findById(id); } } describe('UserService', () => { let userService: UserService; let repository: Mocked; let logger: Mocked; beforeAll(async () => { const { unit, unitRef } = await TestBed.solitary(UserService).compile(); userService = unit; repository = unitRef.get('UserRepository'); logger = unitRef.get('Logger'); }); it('should fetch user from repository', async () => { repository.findById.mockResolvedValue({ id: '1', name: 'Alice' }); const user = await userService.getUser('1'); expect(user.name).toBe('Alice'); expect(logger.info).toHaveBeenCalledWith('Fetching user 1'); }); }); ``` -------------------------------- ### Logger Interface Definition Source: https://github.com/suites-dev/suites-unit/wiki/Identifiers-And-Tokens Defines a Logger interface used as an example for string/symbol-based tokens. ```typescript interface Logger { log(message: string): void; } ``` -------------------------------- ### Avoid JSDoc Example: Solitary Test Bed Builder Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Shows the JSDoc style to avoid because it only states what the code does without explaining the purpose or benefits. Use this as a contrast to the recommended style. ```typescript /** * Creates a solitary test bed builder. */ ``` -------------------------------- ### Interface JSDoc Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting an interface with JSDoc, including @template, @see, @since, and @example tags. ```typescript /** * [Brief description explaining the interface purpose] * [Additional context about when this interface is used] * * @template [T] [Description of generic parameter if applicable] * @see [link to docs] * @since [version] * * @example * import { Interface } from '@suites/package'; * * const example: Interface = { * // usage example * }; */ export interface InterfaceName { // properties... } ``` -------------------------------- ### Public Method JSDoc Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting a public method with JSDoc, including @description, @since, @template, @param, @returns, @throws, @example, and @see tags. ```typescript /** * @description * [Detailed description of what the method does] * [Explain the use case and when to use this method] * [Include any important details about behavior] * * @since [version] * @template [T] [Description of generic parameter] * @param paramName - [Description of parameter and its purpose] * @returns [Description of what is returned] * @throws {@link ErrorType} [Description of when this error is thrown] * * @example * import { Class } from '@suites/package'; * import { Dependency } from './dependency'; * * // Example usage with context * const result = await instance.method(param); * * @see [link to docs] */ public method(param: Type): ReturnType { // ... } ``` -------------------------------- ### TypeScript - Access injected dependencies by custom tokens Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples After injecting with custom tokens, retrieve each dependency using the same token strings in unitRef.get(). This must be used in conjunction with the previous constructor example. ```TypeScript const database1 = unitRef.get('DATABASE_1'); const database2 = unitRef.get('DATABASE_2'); ``` -------------------------------- ### Mocked usage with Jest mock functions Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/jest/README.md Shows how to use the Mocked type to configure mock return values, async returns, custom implementations, and assertions. The example covers mockReturnValue, mockReturnValueOnce, mockResolvedValue, mockRejectedValue, mockImplementation, and common Jest assertion methods. ```typescript // Return values mock.method.mockReturnValue(value); mock.method.mockReturnValueOnce(value); // Async return values mock.method.mockResolvedValue(value); mock.method.mockRejectedValue(error); // Custom implementations mock.method.mockImplementation((args) => result); // Assertions expect(mock.method).toHaveBeenCalled(); expect(mock.method).toHaveBeenCalledWith(arg1, arg2); expect(mock.method).toHaveBeenCalledTimes(3); ``` -------------------------------- ### InversifyJS class-based injection Source: https://github.com/suites-dev/suites-unit/wiki/Identifiers-And-Tokens Example of class-based injection in InversifyJS. The class itself serves as the identifier for dependency resolution. ```typescript import { injectable, inject } from 'inversify'; @injectable() class UserService { constructor(private apiService: ApiService) {} } ``` -------------------------------- ### NestJS class-based injection Source: https://github.com/suites-dev/suites-unit/wiki/Identifiers-And-Tokens Example of class-based injection in NestJS. The class itself serves as the identifier for dependency resolution. ```typescript import { Injectable, Inject } from '@nestjs/common'; @Injectable() class UserService { constructor(private apiService: ApiService) {} } ``` -------------------------------- ### TypeScript - Inject custom tokens for multiple injections in UserService Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Use unique custom tokens with @Inject to mock multiple instances of the same class. Without tokens, unitRef.get() only returns the first injected dependency. This example defines two database injects. ```TypeScript class UserService { public constructor( @Inject('DATABASE_1') private readonly database1: Database, @Inject('DATABASE_2') private readonly database2: Database, ) {} public async getUsers() { const users1 = await this.database1.getUsers(); const users2 = await this.database2.getUsers(); return [...users1, ...users2]; } } ``` -------------------------------- ### Run the test suite Source: https://github.com/suites-dev/suites-unit/blob/master/CONTRIBUTING.md Executes the project's test suite to verify everything is functioning correctly. ```bash pnpm test ``` -------------------------------- ### TestBed.create(classToTest): TestBedBuilder Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Initializes the TestBed with the class you want to test and returns a TestBedBuilder instance for further configuration and compilation. ```APIDOC ## TestBed.create(classToTest): TestBedBuilder ### Description Initializes the TestBed with the class you want to test and returns a TestBedBuilder instance for further configuration and compilation. ### Method create ### Endpoint TestBed.create ### Parameters #### Parameters - **classToTest** (TClass) - Required - The class for which you want to create an instance ### Returns - **TestBedBuilder** - A builder instance for configuring and compiling the test unit ### Request Example ```typescript const { unit, unitRef } = TestBed.create(UserService); ``` ### Response #### Success Response Returns a TestBedBuilder instance that can be used to compile the test unit and access mocked dependencies. #### Response Example ```typescript const { unit, unitRef } = TestBed.create(UserService); ``` ``` -------------------------------- ### Documenting generic type parameters (brief) Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Documents generic type parameters with brief explanations of what each represents. ```typescript /** * @template TClass The type of the class to be tested. * @template TDependency The type of the dependency being retrieved. */ ``` -------------------------------- ### Documenting method overloads for UnitReference.get Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Shows how to document overloaded methods with separate JSDoc blocks for each signature, including @since, @template, @param, @throws, and @returns tags. ```typescript export interface UnitReference { /** * 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 IdentifierNotFoundError} If the dependency is not found. * @returns The mocked object corresponding to the provided type identifier. */ get(type: Type): 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 IdentifierNotFoundError} If the dependency is not found. * @returns The mocked object corresponding to the provided string-based token. */ get(token: string): StubbedInstance; } ``` -------------------------------- ### Access TestBed unit and unitRef Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Shows how to access the class instance and its dependency mocks after compiling a TestBed. The `unit` property is the actual instance, and `unitRef.get()` retrieves the automatically generated mock for a dependency. ```typescript const { unit, unitRef } = TestBed.create(UserService).compile(); const userService = unit; const database = unitRef.get(Database); ``` -------------------------------- ### MockOverride.using(mockImplementation) Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples The `.using(mockImplementation)` method specifies the mock implementation to be used for a mocked dependency. It returns a TestBedBuilder for chaining. ```APIDOC ## MockOverride.using(mockImplementation) ### Description Specifies the mock implementation to be used for a mocked dependency. The mocked dependency will be replaced completely without any stubs; methods not explicitly defined in the mockImplementation object will have no behavior. ### Method using ### Signature `.using(mockImplementation: TImpl): TestBedBuilder` ### Parameters - **mockImplementation** (TImpl) - Required - The mock implementation for the mocked dependency. ### Returns `TestBedBuilder` ### Example ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock(Database) .using({ getUsers: async () => [{ id: 1, name: 'John' }] }) .compile(); ``` ### Notes When using `.using()` to provide a mock implementation, the subject being mocked will be replaced completely without any stubs. Methods not explicitly defined in the `mockImplementation` object will not have any behavior. To add stubs for specific methods: ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock(Database) .using({ getUsers: jest.fn().mockReturnValue([{ id: 1, name: 'John' }]) }) .compile(); ``` ``` -------------------------------- ### Mock Token-Based Dependency Source: https://github.com/suites-dev/suites-unit/wiki/Identifiers-And-Tokens Mock a token-based dependency using the token itself with TestBed.create().mock().using().compile(). ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock(LOGGER_TOKEN) .using({ ... }) .compile(); ``` -------------------------------- ### Manual deep mocking with TestBed Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Illustrates manual deep mocking with TestBed. The class under test depends on PrismaService, and the mock provides nested models with jest.fn() methods. Deep mocking is not directly supported and can lead to unexpected behavior; prefer mocking only direct dependencies. ```typescript export class ClassWithModels { public constructor(private models: PrismaService) {} public async findUsers(): Promise { return this.models.user.find(); } } beforeAll(() => { const { unit, unitRef } = TestBed.create(ClassWithModels) .mock(PrismaWrapperService) .using({ models: { user: { find: jest.fn() }, animal: { findUnique: jest.fn() }, }, }) .compile(); }); ``` -------------------------------- ### Mock API usage with Sinon stubs Source: https://github.com/suites-dev/suites-unit/blob/master/packages/doubles/sinon/README.md Shows how to configure Sinon stubs for return values, async results, custom implementations, and assertions using the Mocked type. ```typescript // Return values mock.method.returns(value); mock.method.returnsThis(); // Async return values mock.method.resolves(value); mock.method.rejects(error); // Custom implementations mock.method.callsFake((args) => result); // Assertions expect(mock.method.called).to.be.true; expect(mock.method.calledWith(arg1, arg2)).to.be.true; expect(mock.method.callCount).to.equal(3); ``` -------------------------------- ### Using .using() with mock implementation object Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Provides a mock implementation for a mocked dependency. The subject is replaced completely without any stubs; methods not defined in the object have no behavior. ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock(Database) .using({ getUsers: async () => [{ id: 1, name: 'John' }] }) .compile(); ``` -------------------------------- ### Format: @see links Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Shows the format for @see links in JSDoc comments, pointing to relevant documentation pages on suites.dev. ```typescript @see https://suites.dev/docs/api-reference/api/testbed-api @see https://suites.dev/docs/developer-guide/unit-tests ``` -------------------------------- ### MockOverride.using(value) Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples The `.using(value)` method allows specifying fixed values to be used for mocked dependencies. It returns a TestBedBuilder for chaining. ```APIDOC ## MockOverride.using(value) ### Description Specifies a fixed value to be used for a mocked dependency. This overload is available since v1.2.0. ### Method using ### Signature `.using(value: TValue): TestBedBuilder` ### Parameters - **value** (TValue) - Required - The fixed value for the mocked dependency. ### Returns `TestBedBuilder` ### Example ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock('CUSTOM_TOKEN') .using('some fixed value') .compile(); ``` ``` -------------------------------- ### Mock dependency by token with .mock(token) Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Declares a dependency to be mocked using a string token. For better type safety, specify the type via generic argument like .mock('MY_TOKEN'). ```TypeScript const { unit, unitRef } = TestBed.create(UserService) .mock('CUSTOM_TOKEN') .using({ ... }) .compile(); ``` -------------------------------- ### Documenting generic type parameters (detailed) Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Provides a more detailed explanation of a generic type parameter, emphasizing type safety and consistency. ```typescript /** * @template TClass The type of the class being tested. This generic parameter ensures type safety * and consistency across the testing code. */ ``` -------------------------------- ### Class JSDoc Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting a class with JSDoc. Placeholders like [ClassName] and [version] should be replaced with actual values. ```typescript /** * @description * [Brief description of what the class does and its purpose] * [Additional context about when/why to use this class] * * @class [ClassName] * @see [link to docs] * @since [version] */ export class ClassName { // ... } ``` -------------------------------- ### JSDoc for impl() method Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md JSDoc for the impl() method. It explains the purpose, documents the mockImplementation parameter, and describes the return value. ```typescript /** * Defines a custom implementation for a mocked dependency. This method is used to set up * how the mock should behave when interacted with during tests. * * @since 3.0.0 * @param mockImplementation - A function that receives a stub function and returns a partial * implementation of the dependency. This setup allows testers to specify detailed behavior, * including how methods should respond when invoked. * @returns A TestBedBuilder instance, facilitating a fluent interface that allows further * configuration of the testing environment. */ impl( mockImplementation: (stubFn: Stub>) => DeepPartial ): TestBedBuilder; ``` -------------------------------- ### Using .using() with jest.fn() for stubs Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Adds stubs for specific methods by providing a jest.fn() mock. This is used when you need to define behavior for individual methods. ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock(Database) .using({ getUsers: jest.fn().mockReturnValue([{ id: 1, name: 'John' }]) }) .compile(); ``` -------------------------------- ### tsconfig.json - Enable Decorator Metadata Source: https://github.com/suites-dev/suites-unit/blob/master/packages/di/inversify/README.md Required TypeScript compiler options for the adapter. Set experimentalDecorators and emitDecoratorMetadata to true to support InversifyJS decorators. ```json { "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } } ``` -------------------------------- ### Interface Property Template Source: https://github.com/suites-dev/suites-unit/blob/master/JSDOC_STYLE_GUIDE.md Template for documenting an interface property with description, since version, template, and property tag. ```typescript interface Example { /** * [Description of the property and its purpose] * [Additional context if needed] * * @since [version] * @template [T] [Description if property is generic] * @property [propertyName] [Type and description] */ propertyName: Type; } ``` -------------------------------- ### Mock dependency by type with .mock(type) Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Declares a dependency to be mocked using its type. Returns a MockOverride for chaining .using() and .compile(). ```TypeScript const { unit, unitRef } = TestBed.create(UserService) .mock(Database) .using({ getUsers: async () => [] }) .compile(); ``` -------------------------------- ### Using .using() with fixed value (since v1.2.0) Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Specifies a fixed value for a mocked dependency, useful for tokens or constants. Available since v1.2.0. ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock('CUSTOM_TOKEN') .using('some fixed value') .compile(); ``` -------------------------------- ### .mock(token: string): MockOverride Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Declares a dependency to be mocked using a token string. Use the generic argument for type safety. ```APIDOC ## .mock(token: string): MockOverride ### Description Declares a dependency to be mocked using a token string. Use the generic argument for type safety. ### Method mock ### Parameters - **token** (string) - Required - The token string representing the dependency to be mocked ### Returns MockOverride ### Example ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock('CUSTOM_TOKEN') .using({ ... }) .compile(); ``` ``` -------------------------------- ### String-Based Token Constant Source: https://github.com/suites-dev/suites-unit/wiki/Identifiers-And-Tokens Defines a string-based token constant for dependency injection. ```typescript export const LOGGER_TOKEN = 'LOGGER_TOKEN' ``` -------------------------------- ### .mock(type: Type): MockOverride Source: https://github.com/suites-dev/suites-unit/wiki/TestBed-API-Reference-and-Examples Declares a dependency to be mocked using its type. Returns a MockOverride for further configuration. ```APIDOC ## .mock(type: Type): MockOverride ### Description Declares a dependency to be mocked using its type. Returns a MockOverride for further configuration. ### Method mock ### Parameters - **type** (Type) - Required - The type of the dependency to be mocked ### Returns MockOverride ### Example ```typescript const { unit, unitRef } = TestBed.create(UserService) .mock(Database) .using({ getUsers: async () => [] }) .compile(); ``` ``` -------------------------------- ### InversifyJS: String/Symbol Token Injection Source: https://github.com/suites-dev/suites-unit/wiki/Identifiers-And-Tokens Inject a dependency using a string or symbol token in InversifyJS with @inject. ```typescript import { injectable, inject } from 'inversify'; @injectable() class UserService { constructor(@inject(LOGGER_TOKEN) private logger: Logger) {} } ``` -------------------------------- ### NestJS: String/Symbol Token Injection Source: https://github.com/suites-dev/suites-unit/wiki/Identifiers-And-Tokens Inject a dependency using a string or symbol token in NestJS with @Inject. ```typescript import { Injectable, Inject } from '@nestjs/common'; @Injectable() class UserService { constructor(@Inject(LOGGER_TOKEN) private logger: Logger) {} } ```