{"id":16859,"library":"mock-typeorm","title":"Mock TypeORM","description":"Mock TypeORM is a TypeScript-first library designed to facilitate unit and integration testing of TypeORM-based applications by preventing actual database interactions. It is currently at version 1.0.4 and appears to be actively maintained, indicated by recent GitHub activity and a workflow badge. The package differentiates itself by utilizing Sinon.js for mocking, which makes it compatible with a wide range of Node.js testing frameworks such as Jest, Mocha, and Vitest, offering flexibility that some other mocking approaches (e.g., Jest-specific mocks) might lack. It provides a straightforward API to mock TypeORM's `DataSource`, `EntityManager`, `Transaction`, `QueryBuilder`, and `Repository` methods, enabling developers to control database responses programmatically without needing a real database connection. This approach significantly speeds up tests and makes them more deterministic and isolated, avoiding the complexities and flakiness associated with test databases.","status":"active","version":"1.0.4","language":"javascript","source_language":"en","source_url":"https://github.com/jazimabbas/mock-typeorm","tags":["javascript","typeorm","mocking","mock typeorm","mock-typeorm","typescript","nodejs"],"install":[{"cmd":"npm install mock-typeorm","lang":"bash","label":"npm"},{"cmd":"yarn add mock-typeorm","lang":"bash","label":"yarn"},{"cmd":"pnpm add mock-typeorm","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime peer dependency for creating mocks and stubs. Mock TypeORM uses Sinon internally, making it framework-agnostic.","package":"sinon","optional":false},{"reason":"Peer dependency as Mock TypeORM is designed to mock its functionalities. Ensure compatible versions are installed.","package":"typeorm","optional":false}],"imports":[{"note":"The primary class to instantiate for creating and managing TypeORM mocks. The package is ESM-first, so CommonJS `require` might lead to issues without proper transpilation or configuration.","wrong":"const { MockTypeORM } = require('mock-typeorm');","symbol":"MockTypeORM","correct":"import { MockTypeORM } from 'mock-typeorm';"},{"note":"When defining entity repositories, the `Repository` type should be imported directly from `typeorm`, not `mock-typeorm`. `mock-typeorm` helps create *mocks* of this, but not the type itself.","wrong":"import { Repository } from 'mock-typeorm';","symbol":"Repository","correct":"import { Repository } from 'typeorm';"}],"quickstart":{"code":"import { DataSource, Repository, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';\nimport { MockTypeORM } from 'mock-typeorm';\nimport * as sinon from 'sinon';\n\n@Entity()\nclass User {\n  @PrimaryGeneratedColumn()\n  id!: number;\n\n  @Column()\n  name!: string;\n\n  @Column()\n  email!: string;\n}\n\n// A simple service that uses the UserRepository\nclass UserService {\n  constructor(private userRepository: Repository<User>) {}\n\n  async createUser(name: string, email: string): Promise<User> {\n    const newUser = this.userRepository.create({ name, email });\n    return this.userRepository.save(newUser);\n  }\n\n  async findUserById(id: number): Promise<User | null> {\n    return this.userRepository.findOne({ where: { id } });\n  }\n}\n\ndescribe('UserService', () => {\n  let mockTypeORM: MockTypeORM;\n  let userRepository: Repository<User>;\n  let userService: UserService;\n\n  beforeEach(() => {\n    // Initialize MockTypeORM and reset Sinon stubs before each test\n    mockTypeORM = new MockTypeORM();\n    sinon.restore(); // Ensure stubs from previous tests are cleared\n\n    // Create a mock repository for the User entity\n    userRepository = mockTypeORM.onMock(User);\n\n    // Instantiate the service with the mocked repository\n    userService = new UserService(userRepository);\n  });\n\n  afterEach(() => {\n    // Restore TypeORM's original behavior and clear all mocks\n    mockTypeORM.restore();\n  });\n\n  it('should create a new user', async () => {\n    const userData = { name: 'Alice', email: 'alice@example.com' };\n    const expectedUser = { id: 1, ...userData };\n\n    // Stub the 'save' method of the mocked repository\n    sinon.stub(userRepository, 'save').resolves(expectedUser);\n\n    const result = await userService.createUser(userData.name, userData.email);\n\n    expect(result).toEqual(expectedUser);\n    expect(userRepository.save).toHaveBeenCalledWith(expect.objectContaining(userData));\n  });\n\n  it('should find a user by ID', async () => {\n    const expectedUser = { id: 1, name: 'Bob', email: 'bob@example.com' };\n\n    // Stub the 'findOne' method of the mocked repository\n    sinon.stub(userRepository, 'findOne').resolves(expectedUser);\n\n    const result = await userService.findUserById(1);\n\n    expect(result).toEqual(expectedUser);\n    expect(userRepository.findOne).toHaveBeenCalledWith({ where: { id: 1 } });\n  });\n\n  it('should return null if user not found', async () => {\n    // Stub the 'findOne' method to resolve with null\n    sinon.stub(userRepository, 'findOne').resolves(null);\n\n    const result = await userService.findUserById(99);\n\n    expect(result).toBeNull();\n    expect(userRepository.findOne).toHaveBeenCalledWith({ where: { id: 99 } });\n  });\n});","lang":"typescript","description":"This quickstart demonstrates how to set up `mock-typeorm` in a test suite using Jest (or a compatible framework) to mock a `UserRepository`, stub its methods with Sinon, and verify interactions within a simple `UserService`."},"warnings":[{"fix":"Run `npm install --save-dev sinon @types/sinon` alongside `mock-typeorm`.","message":"`sinon` is a peer dependency and must be installed separately. Failing to install `sinon` (and its types `@types/sinon` for TypeScript projects) will result in runtime errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `mockTypeORM.restore()` in an `afterEach` hook or create a new `MockTypeORM` instance in `beforeEach` for each test to ensure a clean state. If using `sinon` directly, `sinon.restore()` is also an option.","message":"It's crucial to reset the mock state between tests to ensure test isolation. Not doing so can lead to unexpected behavior where mock configurations from one test affect subsequent tests.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure your project uses Node.js version 18.x or higher. Update your Node.js environment if necessary.","message":"The package targets Node.js 18.x and above. Older Node.js versions might encounter compatibility issues, especially with ESM features, as the package is likely designed for modern JavaScript environments.","severity":"breaking","affected_versions":"<1.0.0 (engines field suggests 1.0.x is 18+)"},{"fix":"Thoroughly review your application's data access logic to identify all TypeORM repository methods being used. Explicitly stub each required method on the mock repository (e.g., `sinon.stub(repo, 'find').resolves([])`).","message":"When mocking TypeORM repositories, ensure all methods your service/controller interacts with are explicitly stubbed. If a method is called that hasn't been stubbed, it might lead to undefined behavior or errors, as `mock-typeorm` prevents actual DB calls.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"For TypeScript/ESM projects, use `import { MockTypeORM } from 'mock-typeorm';`. If forced to use CommonJS, ensure your build process correctly transpiles ESM or configure Node.js to handle ESM. Consider switching to ESM if possible.","cause":"This usually happens in CommonJS environments trying to `require` an ESM-first package, or incorrect import syntax.","error":"TypeError: (0, _mockTypeorm.MockTypeORM) is not a constructor"},{"fix":"Install Sinon.js and its TypeScript types: `npm install --save-dev sinon @types/sinon`.","cause":"The `sinon` package is a peer dependency of `mock-typeorm` and must be installed explicitly.","error":"Error: Cannot find module 'sinon'"},{"fix":"Ensure that `mock-typeorm` is initialized and active before TypeORM connection-dependent code runs. Verify that no code attempts to establish a real database connection during unit tests, or that the `DataSource` itself is completely mocked to prevent this error. The primary method is to instantiate `new MockTypeORM()` before your tests.","cause":"`mock-typeorm` intercepts TypeORM calls, but if `TypeORM.initialize()` or a similar connection setup is still implicitly expected by parts of your application, this error can occur if the setup is not properly bypassed or mocked.","error":"ConnectionNotFoundError: Connection \"default\" was not found."}],"ecosystem":"npm","meta_description":null}