### Basic Setup Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Initialize MockTypeORM and reset/restore mocks. ```typescript import { MockTypeORM } from 'mock-typeorm'; const typeorm = new MockTypeORM(); // After each test typeorm.resetAll(); // After all tests typeorm.restore(); ``` -------------------------------- ### Create QueryBuilder Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Examples of creating a QueryBuilder instance from Repository, DataSource, or EntityManager. ```typescript // From Repository const qb = repo.createQueryBuilder('r'); // From DataSource const qb = dataSource.createQueryBuilder(Role, 'r'); // From EntityManager const qb = manager.createQueryBuilder(Role, 'r'); ``` -------------------------------- ### Initialize and Cleanup Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates the basic setup for mock-typeorm, including initialization with MockTypeORM, resetting mocks between tests, and restoring original TypeORM behavior after all tests. ```typescript import { MockTypeORM } from 'mock-typeorm'; import { describe, beforeAll, afterEach, afterAll } from 'vitest'; describe('User Repository', () => { let typeorm: MockTypeORM; beforeAll(() => { typeorm = new MockTypeORM(); }); afterEach(() => { typeorm.resetAll(); // Clear mocks between tests }); afterAll(() => { typeorm.restore(); // Restore original TypeORM behavior }); // tests... }); ``` -------------------------------- ### Async Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Examples of asynchronous methods that require 'await'. ```typescript const role = await repo.findOne({}); // Async const roles = await repo.find(); // Async const saved = await repo.save(role); // Async ``` -------------------------------- ### Installation Source: https://github.com/jazimabbas/mock-typeorm/blob/master/README.md Install the mock-typeorm package and its dependencies. ```bash npm install --save-dev mock-typeorm sinon @types/sinon ``` -------------------------------- ### Sync Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Examples of synchronous methods that do not require 'await'. ```typescript const role = repo.create({}); // Sync - no await const merged = repo.merge(e1, e2); // Sync - no await ``` -------------------------------- ### Test Template Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md A complete Vitest test suite template demonstrating the setup and usage of MockTypeORM. ```typescript import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest'; import { MockTypeORM } from 'mock-typeorm'; import { Entity } from './Entity'; import { dataSource } from './database'; describe('Entity Repository', () => { let typeorm: MockTypeORM; beforeAll(() => { typeorm = new MockTypeORM(); }); afterEach(() => { typeorm.resetAll(); }); afterAll(() => { typeorm.restore(); }); it('should find entities', async () => { const mockData = [{ id: '1' }]; typeorm.onMock(Entity).toReturn(mockData, 'find'); const result = await dataSource.getRepository(Entity).find(); expect(result).toEqual(mockData); }); }); ``` -------------------------------- ### Basic EntityManager Queries Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Example of mocking a basic EntityManager query like findOne. ```typescript const typeorm = new MockTypeORM(); typeorm.onMock(Role).toReturn({ id: '1', name: 'Admin' }, 'findOne'); const role = await dataSource.manager.findOne(Role, { where: { id: '1' } }); console.log(role); // { id: '1', name: 'Admin' } ``` -------------------------------- ### Using Repository Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Standard usage of a TypeORM Repository. ```typescript const repo = dataSource.getRepository(Role); await repo.find(); await repo.findOne({}); await repo.save(role); ``` -------------------------------- ### Result Methods (Async) Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/SUPPORTED_METHODS.md Shows an example of using a result method like 'getOne' after mocking the repository with 'typeorm.onMock'. ```typescript typeorm.onMock(Role).toReturn({ id: '1' }, 'getOne'); const role = await qb.getOne(); // Returns { id: '1' } ``` -------------------------------- ### Basic Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/README.md A basic example demonstrating how to use mock-typeorm with Vitest to mock TypeORM repositories and query builders. ```typescript import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest'; import { MockTypeORM } from 'mock-typeorm'; import { DataSource } from 'typeorm'; import { Role } from './entities'; describe('Role Repository', () => { let typeorm: MockTypeORM; let dataSource: DataSource; beforeAll(() => { typeorm = new MockTypeORM(); dataSource = new DataSource({ /* ... */ }); }); afterEach(() => { typeorm.resetAll(); }); afterAll(() => { typeorm.restore(); }); it('should find all roles', async () => { const mockRoles = [ { id: '1', name: 'Admin' }, { id: '2', name: 'User' } ]; typeorm.onMock(Role).toReturn(mockRoles, 'find'); const repo = dataSource.getRepository(Role); const roles = await repo.find(); expect(roles).toEqual(mockRoles); }); it('should handle errors', async () => { typeorm.onMock(Role).toReturn(new Error('DB error'), 'find'); const repo = dataSource.getRepository(Role); await expect(repo.find()).rejects.toThrow('DB error'); }); it('should mock QueryBuilder results', async () => { const mockRole = { id: '1', name: 'Admin' }; typeorm.onMock(Role).toReturn(mockRole, 'getOne'); const qb = dataSource.createQueryBuilder(Role, 'role'); const role = await qb .where('role.id = :id', { id: '1' }) .getOne(); expect(role).toEqual(mockRole); }); }); ``` -------------------------------- ### Complete Test Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md A comprehensive example demonstrating how to use Mock TypeORM in a test suite for a User Service, including mocking repository methods, handling errors, and using QueryBuilder. ```typescript import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest'; import { MockTypeORM } from 'mock-typeorm'; import { DataSource } from 'typeorm'; import { Role } from './entities/role'; import { User } from './entities/user'; describe('User Service', () => { let typeorm: MockTypeORM; let dataSource: DataSource; beforeAll(() => { typeorm = new MockTypeORM(); dataSource = new DataSource({ type: 'mysql', host: 'localhost', username: 'root', password: 'password', database: 'test' }); }); afterEach(() => { typeorm.resetAll(); }); afterAll(() => { typeorm.restore(); }); it('should find a user by ID', async () => { const mockUser = { id: '1', name: 'John Doe' }; typeorm.onMock(User).toReturn(mockUser, 'findOne'); const user = await dataSource.getRepository(User).findOne({ where: { id: '1' } }); expect(user).toEqual(mockUser); }); it('should save and return saved user', async () => { const newUser = { name: 'Jane Doe' }; const savedUser = { id: '2', ...newUser }; typeorm .onMock(User) .toReturn(savedUser, 'create') .toReturn(savedUser, 'save'); const userRepo = dataSource.getRepository(User); const created = userRepo.create(newUser); const result = await userRepo.save(created); expect(result).toEqual(savedUser); }); it('should handle errors gracefully', async () => { const error = new Error('Database connection failed'); typeorm.onMock(Role).toReturn(error, 'find'); const roleRepo = dataSource.getRepository(Role); await expect(roleRepo.find()).rejects.toThrow('Database connection failed'); }); it('should use QueryBuilder correctly', async () => { const mockRoles = [ { id: '1', name: 'Admin' }, { id: '2', name: 'User' } ]; typeorm.onMock(Role).toReturn(mockRoles, 'getMany'); const qb = dataSource.createQueryBuilder(Role, 'role'); const roles = await qb .where('role.active = :active', { active: true }) .orderBy('role.name', 'ASC') .getMany(); expect(roles).toEqual(mockRoles); }); }); ``` -------------------------------- ### Async Method Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/SUPPORTED_METHODS.md Demonstrates how to use async methods with await. ```typescript typeorm.onMock(Role).toReturn([...], 'find'); const roles = await repo.find(); // Must await ``` -------------------------------- ### EntityManager Query Methods Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/SUPPORTED_METHODS.md Provides an example of mocking an entity class and then using an EntityManager query method like 'findOne'. ```typescript typeorm.onMock(EntityClass).toReturn(data, 'methodName'); const result = await dataSource.manager.findOne(EntityClass, {}); ``` -------------------------------- ### Transaction Pattern Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Example of using transactions with EntityManager, showing that the callback manager is mocked. ```typescript const result = await manager.transaction(async (trx) => { const roles = await trx.find(Role); // Uses mocked find const users = await trx.find(User); return { roles, users }; }); ``` -------------------------------- ### Development Dependencies Source: https://github.com/jazimabbas/mock-typeorm/blob/master/README.md Install development dependencies for the project. ```bash pnpm install ``` -------------------------------- ### Reset Everything Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Reset all mocks for all repositories. ```typescript typeorm.resetAll(); // All repositories ``` -------------------------------- ### Using EntityManager Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates how to use EntityManager for TypeORM operations and how to mock its methods. ```typescript const manager = dataSource.manager; await manager.find(Role, {}); await manager.findOne(Role, {}); await manager.save(role); ``` ```typescript typeorm.onMock(Role).toReturn([...], 'find'); // Works with repo.find() AND manager.find(Role) ``` -------------------------------- ### createQueryBuilder and createQueryRunner Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to mock and use createQueryBuilder from DataSource, Repository, and EntityManager, and how to mock createQueryRunner. ```typescript const typeorm = new MockTypeORM(); typeorm.onMock(Role).toReturn({ id: '1' }, 'getOne'); // DataSource.createQueryBuilder const qb1 = dataSource.createQueryBuilder(Role, 'role'); const role1 = await qb1.getOne(); // Repository.createQueryBuilder const repo = dataSource.getRepository(Role); const qb2 = repo.createQueryBuilder('role'); const role2 = await qb2.getOne(); // EntityManager.createQueryBuilder const qb3 = dataSource.manager.createQueryBuilder(Role, 'role'); const role3 = await qb3.getOne(); ``` -------------------------------- ### MockState Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/types.md Example structure of the MockState object. ```typescript { 'Role': { 'findOne': { 0: { id: '1', name: 'Admin' }, 1: { id: '2', name: 'User' } }, 'find': { 0: [{ id: '1' }, { id: '2' }] } }, 'User': { 'findOne': { 0: { id: 'user1', name: 'John' } } } } ``` -------------------------------- ### Non-Async Method Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/SUPPORTED_METHODS.md Demonstrates how to use non-async methods without await. ```typescript typeorm.onMock(Role).toReturn({...}, 'create'); const role = repo.create({...}); // No await needed ``` -------------------------------- ### Mocking null and Falsy Values Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Provides examples of mocking methods to return `null`, empty arrays `[]`, `undefined`, and `false`, covering various falsy return scenarios. ```typescript const typeorm = new MockTypeORM(); // Mock with null typeorm.onMock(Role).toReturn(null, 'findOne'); const role = await dataSource.getRepository(Role).findOne({}); // null // Mock with empty array typeorm.onMock(User).toReturn([], 'find'); const users = await dataSource.getRepository(User).find(); // [] // Mock with undefined typeorm.onMock(Post).toReturn(undefined, 'findOneOrFail'); const post = await dataSource.getRepository(Post).findOneOrFail({}); // undefined // Mock with false typeorm.onMock(Role).toReturn(false, 'hasId'); const hasId = await dataSource.getRepository(Role).hasId({}); // false ``` -------------------------------- ### Synchronous Methods Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/SUPPORTED_METHODS.md Illustrates how to mock a repository to return a SQL string for a synchronous method like 'getSql'. ```typescript typeorm.onMock(Role).toReturn('SELECT * FROM roles', 'getSql'); const sql = qb.getSql(); // Returns synchronously ``` -------------------------------- ### Constructor Usage Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/types.md Example of using the Constructor type with entity classes. ```typescript class Role { id: string; name: string; } // Using constructor type typeorm.onMock(Role); // Role is Constructor // Using string name (for EntitySchema) typeorm.onMock('RoleSchema'); // string name ``` -------------------------------- ### Mock EntityManager Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock methods on the EntityManager. ```typescript typeorm.onMock(Role).toReturn([{ id: '1' }], 'find'); const roles = await manager.find(Role, {}); ``` -------------------------------- ### EntityManager create and merge Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Illustrates mocking EntityManager create and merge methods, noting they are not asynchronous. ```typescript const typeorm = new MockTypeORM(); const mockRole = { id: '1', name: 'Admin', isActive: true }; typeorm .onMock(Role) .toReturn(mockRole, 'create') .toReturn({ ...mockRole, name: 'Updated' }, 'merge'); // Note: create and merge are handled specially // create is not async const created = dataSource.manager.create(Role, { name: 'Admin' }); console.log(created); // { id: '1', name: 'Admin', isActive: true } const merged = dataSource.manager.merge(Role, created, { name: 'Updated' }); console.log(merged); // { id: '1', name: 'Updated', isActive: true } ``` -------------------------------- ### MockHistory Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/types.md Example structure of the MockHistory object. ```typescript { 'Role': { 'findOne': 1, // Next call will get mock at index 1 'find': 0 // Next call will get mock at index 0 } } ``` -------------------------------- ### Constructor Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/api-reference/MockTypeORM.md Initialize a new MockTypeORM instance. All TypeORM methods are now mocked. ```typescript import { MockTypeORM } from 'mock-typeorm'; const typeorm = new MockTypeORM(); // All TypeORM methods are now mocked ``` -------------------------------- ### Mock Repository.save() Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock the save() method of a repository. ```typescript typeorm.onMock(Role).toReturn({ id: '1', name: 'Admin' }, 'save'); const saved = await repo.save(role); ``` -------------------------------- ### SetMock Usage Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/types.md Example of using the SetMock interface to configure mock return values. ```typescript const typeorm = new MockTypeORM(); typeorm .onMock(Role) .toReturn({ id: '1' }, 'findOne') .toReturn([{ id: '1' }], 'find'); ``` -------------------------------- ### EntityManager save/remove Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates mocking EntityManager save and remove operations. ```typescript const typeorm = new MockTypeORM(); typeorm .onMock(Role) .toReturn({ id: '1', name: 'Admin' }, 'save') .toReturn({ id: '1', name: 'Admin' }, 'remove'); const role = dataSource.manager.create(Role, { name: 'Admin' }); const saved = await dataSource.manager.save(role); // { id: '1', name: 'Admin' } const removed = await dataSource.manager.remove(role); // { id: '1', name: 'Admin' } ``` -------------------------------- ### QueryRunner Mocking Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Illustrates mocking QueryRunner methods like connect, startTransaction, commitTransaction, and release, and how to interact with the mocked manager within a transaction. ```typescript const typeorm = new MockTypeORM(); typeorm.onMock(Role).toReturn([{ id: '1', name: 'Admin' }], 'find'); const queryRunner = dataSource.createQueryRunner(); // QueryRunner methods are stubbed with Sinon await queryRunner.connect(); await queryRunner.startTransaction(); const roles = await queryRunner.manager.find(Role); console.log(roles); // [{ id: '1', name: 'Admin' }] await queryRunner.commitTransaction(); await queryRunner.release(); ``` -------------------------------- ### Mock Repository.findOne() Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock the findOne() method of a repository. ```typescript typeorm.onMock(Role).toReturn({ id: '1' }, 'findOne'); const role = await repo.findOne({}); ``` -------------------------------- ### Synchronous QueryBuilder Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to mock synchronous QueryBuilder methods like getSql, getQuery, and getQueryAndParameters. ```typescript const typeorm = new MockTypeORM(); typeorm .onMock(Role) .toReturn('SELECT * FROM roles WHERE id = ?', 'getSql') .toReturn('SELECT * FROM roles WHERE id = ?', 'getQuery') .toReturn({ query: 'SELECT...', parameters: [1] }, 'getQueryAndParameters'); const qb = dataSource.createQueryBuilder(Role, 'role'); const sql = qb.getSql(); // String, no await const query = qb.getQuery(); // String, no await const queryAndParams = qb.getQueryAndParameters(); // Object, no await ``` -------------------------------- ### Mock Data by Type - String (for getSql) Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock a string return value for getSql. ```typescript typeorm.onMock(Role).toReturn('SELECT * FROM roles', 'getSql'); ``` -------------------------------- ### Mock Raw Query Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates mocking a raw SQL query executed via QueryBuilder. ```typescript typeorm.onMock(Role).toReturn('SELECT * FROM roles', 'getSql'); const sql = qb.getSql(); // Synchronous ``` -------------------------------- ### Mock with QueryBuilder Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock a QueryBuilder method. ```typescript typeorm.onMock(Role).toReturn([{ id: '1' }], 'getMany'); const roles = await repo .createQueryBuilder('r') .where('r.id = :id', { id: '1' }) .getMany(); ``` -------------------------------- ### Mock EntitySchema Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock using an EntitySchema name. ```typescript const schema = new EntitySchema({ name: 'User', /* ... */ }); typeorm.onMock('User').toReturn({ id: '1' }, 'findOne'); const user = await repo.findOne({}); ``` -------------------------------- ### Chain QueryBuilder Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Illustrates chaining various methods on a QueryBuilder instance and executing the query. ```typescript const roles = await qb .where('r.id = :id', { id: '1' }) // Returns qb .andWhere('r.active = true') // Returns qb .orderBy('r.name', 'ASC') // Returns qb .limit(10) // Returns qb .getMany(); // Returns Promise ``` -------------------------------- ### Chainable Methods Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/METHOD_MATRIX.md Demonstrates how chainable methods on a QueryBuilder return the QueryBuilder instance for chaining. ```typescript qb.where(...).andWhere(...).select().orderBy(...).getMany() ``` ```typescript const qb = repo.createQueryBuilder('e'); qb.where('e.id = 1'); // Returns qb qb.orderBy('e.name', 'ASC'); // Returns qb const result = qb.getOne(); // Returns Promise ``` -------------------------------- ### Basic Repository.find() Mock Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/INTERNALS.md Example of mocking a basic repository find() method. ```typescript const typeorm = new MockTypeORM(); typeorm.onMock(Role).toReturn([{ id: '1' }], 'find'); const roles = await dataSource.getRepository(Role).find(); ``` -------------------------------- ### Mocking Errors Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to configure a mock method to throw an error, simulating a failure scenario like a database connection issue. ```typescript const typeorm = new MockTypeORM(); // Mock method to throw an error typeorm.onMock(Role).toReturn(new Error('Database connection failed'), 'find'); const repository = dataSource.getRepository(Role); try { await repository.find(); } catch (error) { console.log(error.message); // 'Database connection failed' } ``` -------------------------------- ### EntityManager Transactions Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to mock EntityManager transactions, where the mocked manager is passed to the callback. ```typescript const typeorm = new MockTypeORM(); typeorm .onMock(Role) .toReturn([{ id: '1', name: 'Admin' }], 'find'); // transaction is mocked to pass the manager to the callback const result = await dataSource.manager.transaction(async (manager) => { const roles = await manager.find(Role); return roles; }); console.log(result); // [{ id: '1', name: 'Admin' }] ``` -------------------------------- ### Mock Sequential Calls Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock sequential calls to the same method. ```typescript typeorm .onMock(Role) .toReturn({ id: '1' }, 'findOne') .toReturn({ id: '2' }, 'findOne') .toReturn({ id: '3' }, 'findOne'); await repo.findOne(); // { id: '1' } await repo.findOne(); // { id: '2' } await repo.findOne(); // { id: '3' } ``` -------------------------------- ### Single Repository Method Mocking Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to mock a single method of a repository, specifically the `findOne` call for the `Role` entity, and then demonstrates retrieving the mocked data. ```typescript import { MockTypeORM } from 'mock-typeorm'; import { Role } from './entities/role'; import { dataSource } from './database'; const typeorm = new MockTypeORM(); // Mock a single findOne call typeorm.onMock(Role).toReturn({ id: '1', name: 'Admin' }, 'findOne'); const repository = dataSource.getRepository(Role); const role = await repository.findOne({ where: { id: '1' } }); console.log(role); // { id: '1', name: 'Admin' } ``` -------------------------------- ### Mocking with EntitySchema Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/API_INDEX.md Example of mocking a repository using an EntitySchema. ```typescript const UserSchema = new EntitySchema({ name: 'User', /* ... */ }); typeorm.onMock('User').toReturn({ id: '1' }, 'findOne'); // Use EntitySchema instance const user = await dataSource.getRepository(UserSchema).findOne({}); ``` -------------------------------- ### Reset All Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Reset all mocked methods for a specific entity. ```typescript typeorm.onMock(Role).reset(); // All Role methods reset ``` -------------------------------- ### Mock Data by Type - Null/Undefined Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock null or undefined return values. ```typescript typeorm.onMock(Role).toReturn(null, 'findOne'); typeorm.onMock(Role).toReturn(undefined, 'findOneOrFail'); ``` -------------------------------- ### EntityManager with EntitySchema Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates mocking EntityManager methods when using EntitySchema, referencing the schema by its string name. ```typescript const typeorm = new MockTypeORM(); // Using EntitySchema string name typeorm.onMock('UserEntitySchema').toReturn({ id: '1', name: 'John' }, 'findOne'); const userSchema = new EntitySchema({ name: 'UserEntitySchema', tableName: 'users', columns: {} }); const user = await dataSource.manager.findOne(userSchema, { where: { id: '1' } }); console.log(user); // { id: '1', name: 'John' } ``` -------------------------------- ### Mocking String Return Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/METHOD_MATRIX.md Example of mocking a TypeORM query builder method to return a string for 'getSql'. ```typescript typeorm.onMock(E).toReturn('SELECT * FROM table', 'getSql'); ``` -------------------------------- ### Troubleshooting: Method returns {} Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Solution for when a method returns an empty object, indicating it was not mocked. ```typescript typeorm.onMock(Role).toReturn(data, 'findOne'); ``` -------------------------------- ### Using Entity Classes Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to mock entities using TypeORM entity classes, where MockTypeORM uses the class name to identify the entity for mocking. ```typescript import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'; import { MockTypeORM } from 'mock-typeorm'; @Entity() class Role { @PrimaryGeneratedColumn('uuid') id: string; @Column() name: string; } const typeorm = new MockTypeORM(); typeorm.onMock(Role).toReturn({ id: '1', name: 'Admin' }, 'findOne'); // MockTypeORM uses the class name: 'Role' const role = await dataSource.getRepository(Role).findOne({}); ``` -------------------------------- ### Reset All Methods for Repository Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to reset all mocked methods for a specific repository, effectively clearing all mock data and return values for that repository. ```typescript const typeorm = new MockTypeORM(); typeorm .onMock(Role) .toReturn({ id: '1' }, 'findOne') .toReturn([{ id: '1' }], 'find') .toReturn({ id: '1' }, 'save'); // Reset all methods for Role typeorm.onMock(Role).reset(); const repo = dataSource.getRepository(Role); await repo.findOne({}); // Returns {} await repo.find({}); // Returns {} await repo.save({}); // Returns {} ``` -------------------------------- ### Mocking EntityManager Methods Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/types.md Demonstrates how to mock 'findOne' and 'save' methods of EntityManager using typeorm.onMock. ```typescript typeorm.onMock(Role).toReturn({ id: '1' }, 'findOne'); const role = await dataSource.manager.findOne(Role, {}); typeorm.onMock(Role).toReturn({ id: '1', name: 'Admin' }, 'save'); const saved = await dataSource.manager.save(role); ``` -------------------------------- ### Using EntitySchema Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to mock entities using TypeORM EntitySchema, where MockTypeORM uses the schema name string to identify the entity for mocking. ```typescript import { EntitySchema } from 'typeorm'; import { MockTypeORM } from 'mock-typeorm'; const UserSchema = new EntitySchema({ name: 'UserEntitySchema', tableName: 'users', columns: {} }); const typeorm = new MockTypeORM(); // Use the schema name string typeypeorm.onMock('UserEntitySchema').toReturn({ id: '1', name: 'John' }, 'findOne'); const user = await dataSource.getRepository(UserSchema).findOne({}); ``` -------------------------------- ### DataSource Lifecycle Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how Mock TypeORM stubs default DataSource lifecycle methods like initialize, synchronize, runMigrations, and close to be no-ops. ```typescript const typeorm = new MockTypeORM(); // DataSource methods are stubbed but don't return specific values without mocking const dataSource = new DataSource({ type: 'mysql', host: 'localhost', username: 'root', password: 'password', database: 'test' }); // These are mocked to be no-ops by default await dataSource.initialize(); // No error await dataSource.synchronize(); // No error await dataSource.runMigrations(); // No error await dataSource.close(); // No error ``` -------------------------------- ### Chain multiple mocks Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/README.md Example demonstrating chaining multiple mock configurations for the Role entity. ```typescript typeorm .onMock(Role) .toReturn([{ id: '1' }], 'find') .toReturn({ id: '1' }, 'findOne') .toReturn({ id: '1' }, 'save'); ``` -------------------------------- ### State Management Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/INTERNALS.md Illustrates state isolation with multiple MockTypeORM instances and the potential for interference. ```typescript const typeorm1 = new MockTypeORM(); const typeorm2 = new MockTypeORM(); typeorm1.onMock(Role).toReturn({ id: '1' }, 'findOne'); typeorm2.onMock(Role).toReturn({ id: '2' }, 'findOne'); // Both instances modify the same Sinon stubs on TypeORM prototypes! // This means they interfere with each other - only the last configured mock wins ``` -------------------------------- ### EntityManager Query Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Covers mocking various EntityManager query methods like count, find, findOne, findAndCount, query, increment, and decrement. ```typescript const typeorm = new MockTypeORM(); typeorm .onMock(Role) .toReturn(100, 'count') .toReturn([{ id: '1' }], 'find') .toReturn({ id: '1' }, 'findOne') .toReturn([{ id: '1' }, 50], 'findAndCount') .toReturn([{ id: '1', id2: '2' }], 'query') .toReturn(5, 'increment') .toReturn(5, 'decrement'); const count = await dataSource.manager.count(Role); const found = await dataSource.manager.find(Role, {}); const one = await dataSource.manager.findOne(Role, {}); const andCount = await dataSource.manager.findAndCount(Role, {}); const query = await dataSource.manager.query('SELECT * FROM roles'); const incremented = await dataSource.manager.increment(Role, {}, 'count', 5); const decremented = await dataSource.manager.decrement(Role, {}, 'count', 5); ``` -------------------------------- ### Mock QueryBuilder Result Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Shows how to mock the result of a QueryBuilder's getMany() method. ```typescript typeorm.onMock(Role).toReturn([{ id: '1' }], 'getMany'); const roles = await qb.getMany(); ``` -------------------------------- ### Resetting Mocks Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/README.md Examples showing how to reset individual methods, all methods for a specific entity, or all mocks. ```typescript typeorm.onMock(Role).reset('findOne'); // Reset one method typeorm.onMock(Role).reset(); // Reset all methods for Role typeorm.resetAll(); // Reset everything ``` -------------------------------- ### Using String Names Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Provides an alternative way to mock entities using their string names, which can be used for EntitySchema or as a general alternative to passing class references. ```typescript const typeorm = new MockTypeORM(); // Mock using string (for EntitySchema or as alternative) typeorm.onMock('Role').toReturn({ id: '1', name: 'Admin' }, 'findOne'); const role = await dataSource.getRepository('Role').findOne({}); ``` -------------------------------- ### Reset Specific Method Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to reset a specific mocked method for a repository, allowing other mocked methods for the same repository to retain their mock data. ```typescript const typeorm = new MockTypeORM(); typeorm .onMock(Role) .toReturn({ id: '1' }, 'findOne') .toReturn([{ id: '1' }], 'find'); // Reset only findOne, find still returns mocked data typeorm.onMock(Role).reset('findOne'); const repo = dataSource.getRepository(Role); await repo.findOne({}); // Returns {} await repo.find({}); // Returns [{ id: '1' }] ``` -------------------------------- ### Mocking Multiple Repositories Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/README.md Example demonstrating how to mock multiple repositories within a single test by using multiple `onMock()` calls. ```typescript typeorm.onMock(Role).toReturn([...], 'find'); typeorm.onMock(User).toReturn([...], 'find'); ``` -------------------------------- ### Repository Name Resolution for Repository Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/INTERNALS.md Example of how the repository name is resolved when stubbing methods on `Repository.prototype`. ```typescript // In Repository.prototype stub Sinon.stub(Repository.prototype, method as any).callsFake(function(this: any) { const repositoryName = self.getRepositoryName( this?.target, // Entity class or EntitySchema this?.target?.name ?? "" ); // ... }); ``` -------------------------------- ### Mocking Object Return Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/METHOD_MATRIX.md Examples of mocking TypeORM repository methods to return objects for 'delete' and 'insert'. ```typescript typeorm.onMock(E).toReturn({ affected: 1 }, 'delete'); typeorm.onMock(E).toReturn({ generatedMaps: [...], raw: [...] }, 'insert'); ``` -------------------------------- ### Troubleshooting: Error when mocking create/merge/transaction Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Information that methods like create, merge, and transaction do not use the standard `toReturn()` for mocking and have built-in mock behavior. ```typescript // DON'T try to mock these: typeorm.onMock(Role).toReturn(data, 'create'); // Won't work as expected // Use them normally - they have built-in mock behavior const role = manager.create(Role, { name: 'Admin' }); ``` -------------------------------- ### Repository Name Resolution for QueryBuilder Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/INTERNALS.md Example of how the repository name is tracked using `__repositoryName` when stubbing methods on `SelectQueryBuilder.prototype`. ```typescript // In SelectQueryBuilder.prototype stub Sinon.stub(SelectQueryBuilder.prototype, method).callsFake(function(param: any) { const repositoryName = this.__repositoryName ?? param?.name; this.__repositoryName = repositoryName; // Store for next method in chain return this; // Self-reference methods return this }); ``` -------------------------------- ### Reset All Mocks Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Illustrates how to reset all mocks for all repositories at once, clearing all mocked data and return values across the entire Mock TypeORM instance. ```typescript const typeorm = new MockTypeORM(); typeorm.onMock(Role).toReturn({ id: '1' }, 'findOne'); typeorm.onMock(User).toReturn({ id: '1' }, 'findOne'); // Reset all mocks for all repositories typeorm.resetAll(); const roleRepo = dataSource.getRepository(Role); const userRepo = dataSource.getRepository(User); await roleRepo.findOne({}); // Returns {} await userRepo.findOne({}); // Returns {} ``` -------------------------------- ### Self-Reference (Chainable) Methods Example Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/SUPPORTED_METHODS.md Demonstrates how self-reference methods return the QueryBuilder itself for chaining, and how they are mocked to return 'this' automatically. ```typescript const qb = repository.createQueryBuilder('alias'); const result = await qb .where('alias.id = :id', { id: 1 }) // Self-reference method .select() // Self-reference method .getOne(); // Result method ``` -------------------------------- ### Mocking Tuple Return Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/METHOD_MATRIX.md Examples of mocking TypeORM repository methods to return tuples for 'findAndCount' and 'getQueryAndParameters'. ```typescript typeorm.onMock(E).toReturn([[{ id: '1' }], 5], 'findAndCount'); typeorm.onMock(E).toReturn([['SELECT...', []], 'getQueryAndParameters']); ``` -------------------------------- ### Troubleshooting: Multiple MockTypeORM instances interfere Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Guidance on avoiding interference by using only one instance of MockTypeORM per test suite. ```typescript const typeorm = new MockTypeORM(); // Good const typeorm2 = new MockTypeORM(); // Causes interference ``` -------------------------------- ### Methods Union Type Example Usage Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/types.md Example of using the Methods union type. ```typescript const method: Methods = 'find'; // Valid const method2: Methods = 'findOne'; // Valid const method3: Methods = 'save'; // Valid typeorm.onMock(Role).toReturn(data, method); ``` -------------------------------- ### Mocking Number Return Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/METHOD_MATRIX.md Examples of mocking TypeORM repository methods to return numbers for 'count', 'sum', etc. ```typescript typeorm.onMock(E).toReturn(100, 'count'); typeorm.onMock(E).toReturn(5000, 'sum'); ``` -------------------------------- ### Linting Source: https://github.com/jazimabbas/mock-typeorm/blob/master/README.md Run the project's linting process. ```bash pnpm run lint ``` -------------------------------- ### Query Execution Methods Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to mock various query execution methods for QueryBuilder, including single results, arrays, counts, existence checks, and raw data. ```typescript const typeorm = new MockTypeORM(); const Role = class { id: string; name: string; }; typeorm .onMock(Role) .toReturn({ id: '1' }, 'getOne') // Single result .toReturn([{ id: '1' }, { id: '2' }], 'getMany') // Array of results .toReturn([{ id: '1' }], 1, 'getManyAndCount') // Returns tuple .toReturn(5, 'getCount') // Numeric count .toReturn(true, 'getExists') // Boolean exists .toReturn({ id: 1, raw: 'data' }, 'getRawOne') // Raw data .toReturn([{ id: 1, raw: 'data' }], 'getRawMany'); // Array of raw const qb = dataSource.createQueryBuilder(Role, 'role'); const one = await qb.getOne(); const many = await qb.getMany(); const count = await qb.getCount(); const exists = await qb.getExists(); ``` -------------------------------- ### Mock Errors Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock a method to throw an error. ```typescript typeorm.onMock(Role).toReturn(new Error('DB error'), 'find'); await expect(repo.find()).rejects.toThrow('DB error'); ``` -------------------------------- ### Repository Method Mocking Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/SUPPORTED_METHODS.md Demonstrates how to mock repository methods using mock-typeorm. ```typescript typeorm.onMock(EntityClass).toReturn(data, 'methodName'); ``` -------------------------------- ### Special Handling for Repository.create() and EntityManager.create() Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/INTERNALS.md Demonstrates the non-async behavior of `create()` methods, which return data synchronously without a Promise wrapper. ```typescript if (method === "create") { return mockMethod(self, method, repositoryName); // No Promise wrapper } ``` -------------------------------- ### Testing Source: https://github.com/jazimabbas/mock-typeorm/blob/master/README.md Run the project's tests. ```bash pnpm run test ``` -------------------------------- ### Error Simulation Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/API_INDEX.md Example of simulating an error when a mocked method is called. ```typescript const error = new Error('Database connection failed'); typeorm.onMock(Role).toReturn(error, 'find'); await expect(repo.find()).rejects.toThrow('Database connection failed'); ``` -------------------------------- ### Mock Data by Type - Error Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock an error return value. ```typescript const error = new Error('Connection failed'); typeorm.onMock(Role).toReturn(error, 'find'); ``` -------------------------------- ### Multiple Repository Methods Mocking Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Illustrates mocking multiple methods (`find`, `findOne`, `save`, `update`) for the `Role` entity in a single chain, and then executing these mocked methods. ```typescript const typeorm = new MockTypeORM(); typeorm .onMock(Role) .toReturn([{ id: '1', name: 'Admin' }, { id: '2', name: 'User' }], 'find') .toReturn({ id: '1', name: 'Admin' }, 'findOne') .toReturn({ id: '1', name: 'Admin Updated' }, 'save') .toReturn({ affected: 1 }, 'update'); const repository = dataSource.getRepository(Role); const all = await repository.find(); const one = await repository.findOne({}); const saved = await repository.save(one); const updated = await repository.update({ id: '1' }, { name: 'Admin Updated' }); ``` -------------------------------- ### Reset Specific Method Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Reset a specific mocked method for an entity. ```typescript typeorm.onMock(Role).toReturn({ id: '1' }, 'findOne'); typeorm.onMock(Role).reset('findOne'); // Now returns {} instead of { id: '1' } ``` -------------------------------- ### QueryBuilder Chain Mock Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/INTERNALS.md Example of mocking a QueryBuilder chain, including where() and getOne(). ```typescript typeorm.onMock(Role).toReturn({ id: '1' }, 'getOne'); const role = await dataSource .createQueryBuilder(Role, 'role') .where('id = :id', { id: '1' }) .getOne(); ``` -------------------------------- ### Mocking with Entity Classes Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/API_INDEX.md Example of mocking a repository using an entity class. ```typescript class Role { id: string; name: string; } typeorm.onMock(Role).toReturn({ id: '1', name: 'Admin' }, 'findOne'); ``` -------------------------------- ### Mock find() Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/README.md Example of mocking the 'find' method for a Role entity. ```typescript typeorm.onMock(Role).toReturn([{ id: '1' }], 'find'); const roles = await repo.find(); ``` -------------------------------- ### Basic QueryBuilder Chain Mocking Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to mock a QueryBuilder method, specifically `getOne`, for the `Role` entity and then execute a basic QueryBuilder chain to retrieve the mocked result. ```typescript const typeorm = new MockTypeORM(); typeorm.onMock(Role).toReturn({ id: '1', name: 'Admin' }, 'getOne'); const repository = dataSource.getRepository(Role); const role = await repository .createQueryBuilder('role') .where('role.id = :id', { id: '1' }) .andWhere('role.active = :active', { active: true }) .select() .getOne(); console.log(role); // { id: '1', name: 'Admin' } ``` -------------------------------- ### File Structure Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/README.md The file structure of the mock-typeorm project. ```tree output/ ├── README.md (this file) ├── QUICK_REFERENCE.md — Fast lookup guide ├── API_INDEX.md — Complete API catalog ├── SUPPORTED_METHODS.md — All mockable methods ├── USAGE_PATTERNS.md — Real-world examples ├── INTERNALS.md — How it works internally ├── types.md — TypeScript types reference └── api-reference/ └── MockTypeORM.md — Main class documentation ``` -------------------------------- ### Mock Null/Empty Results Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock methods to return null or empty arrays. ```typescript typeorm.onMock(Role).toReturn(null, 'findOne'); const role = await repo.findOne({}); // null typeorm.onMock(Role).toReturn([], 'find'); const roles = await repo.find(); // [] ``` -------------------------------- ### Mock error Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/README.md Example of mocking an error for the 'find' method of a Role entity. ```typescript typeorm.onMock(Role).toReturn(new Error('DB error'), 'find'); await expect(repo.find()).rejects.toThrow(); ``` -------------------------------- ### Mock with QueryBuilder Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/README.md Example of mocking a QueryBuilder 'getOne' method for a Role entity. ```typescript typeorm.onMock(Role).toReturn({ id: '1' }, 'getOne'); const role = await qb.where('id = 1').getOne(); ``` -------------------------------- ### Mock Data by Type - Update Result Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock an update result object for delete/update. ```typescript typeorm.onMock(Role).toReturn({ affected: 1 }, 'delete'); ``` -------------------------------- ### Test Soft Deletes Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/SUPPORTED_METHODS.md Demonstrates how to mock soft delete and restore methods. ```typescript typeorm .onMock(Role) .toReturn({ affected: 1 }, 'softDelete') .toReturn({ affected: 1 }, 'restore'); const deleted = await repo.softDelete({ id: '1' }); const restored = await repo.restore({ id: '1' }); ``` -------------------------------- ### Mock Data by Type - Tuple (find + count) Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock a tuple return value for findAndCount. ```typescript typeorm.onMock(Role).toReturn( [[{ id: '1' }], 5], 'findAndCount' ); ``` -------------------------------- ### QueryBuilder Chainable Methods Mocking Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to mock a QueryBuilder method (`getMany`) and then use a chain of QueryBuilder methods like `select`, `where`, `andWhere`, `orderBy`, `limit`, and `offset` to retrieve mocked data. ```typescript const typeorm = new MockTypeORM(); typeorm.onMock(Role).toReturn([{ id: '1', name: 'Admin' }], 'getMany'); const qb = dataSource.createQueryBuilder(Role, 'role'); const roles = await qb .select() .where('role.active = :active', { active: true }) .andWhere('role.deleted = :deleted', { deleted: false }) .orderBy('role.name', 'ASC') .limit(10) .offset(0) .getMany(); ``` -------------------------------- ### Mock Data by Type - Aggregation Result Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock aggregation results like count or sum. ```typescript typeorm.onMock(Role).toReturn(100, 'count'); typeorm.onMock(Role).toReturn(5000, 'sum'); ``` -------------------------------- ### Mock Data by Type - Array of Entities Source: https://github.com/jazimabbas/mock-typeorm/blob/master/_autodocs/QUICK_REFERENCE.md Mock an array of entities return value for find. ```typescript typeorm.onMock(Role).toReturn( [{ id: '1' }, { id: '2' }], 'find' ); ```