Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
MockTypeORM
✓ import { MockTypeORM } from 'mock-typeorm';
✗ const { MockTypeORM } = require('mock-typeorm');
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.
Repository
✓ import { Repository } from 'typeorm';
✗ import { Repository } from 'mock-typeorm';
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.
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`.
import { DataSource, Repository, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { MockTypeORM } from 'mock-typeorm';
import * as sinon from 'sinon';
@Entity()
class User {
@PrimaryGeneratedColumn()
id!: number;
@Column()
name!: string;
@Column()
email!: string;
}
// A simple service that uses the UserRepository
class UserService {
constructor(private userRepository: Repository<User>) {}
async createUser(name: string, email: string): Promise<User> {
const newUser = this.userRepository.create({ name, email });
return this.userRepository.save(newUser);
}
async findUserById(id: number): Promise<User | null> {
return this.userRepository.findOne({ where: { id } });
}
}
describe('UserService', () => {
let mockTypeORM: MockTypeORM;
let userRepository: Repository<User>;
let userService: UserService;
beforeEach(() => {
// Initialize MockTypeORM and reset Sinon stubs before each test
mockTypeORM = new MockTypeORM();
sinon.restore(); // Ensure stubs from previous tests are cleared
// Create a mock repository for the User entity
userRepository = mockTypeORM.onMock(User);
// Instantiate the service with the mocked repository
userService = new UserService(userRepository);
});
afterEach(() => {
// Restore TypeORM's original behavior and clear all mocks
mockTypeORM.restore();
});
it('should create a new user', async () => {
const userData = { name: 'Alice', email: 'alice@example.com' };
const expectedUser = { id: 1, ...userData };
// Stub the 'save' method of the mocked repository
sinon.stub(userRepository, 'save').resolves(expectedUser);
const result = await userService.createUser(userData.name, userData.email);
expect(result).toEqual(expectedUser);
expect(userRepository.save).toHaveBeenCalledWith(expect.objectContaining(userData));
});
it('should find a user by ID', async () => {
const expectedUser = { id: 1, name: 'Bob', email: 'bob@example.com' };
// Stub the 'findOne' method of the mocked repository
sinon.stub(userRepository, 'findOne').resolves(expectedUser);
const result = await userService.findUserById(1);
expect(result).toEqual(expectedUser);
expect(userRepository.findOne).toHaveBeenCalledWith({ where: { id: 1 } });
});
it('should return null if user not found', async () => {
// Stub the 'findOne' method to resolve with null
sinon.stub(userRepository, 'findOne').resolves(null);
const result = await userService.findUserById(99);
expect(result).toBeNull();
expect(userRepository.findOne).toHaveBeenCalledWith({ where: { id: 99 } });
});
});
Debug
Known issues
gotcha`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.fixRun `npm install --save-dev sinon @types/sinon` alongside `mock-typeorm`.
affects: >=1.0.0
gotchaIt'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.fixUse `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.
affects: >=1.0.0
breakingThe 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.fixEnsure your project uses Node.js version 18.x or higher. Update your Node.js environment if necessary.
affects: <1.0.0 (engines field suggests 1.0.x is 18+)
gotchaWhen 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.fixThoroughly 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([])`).
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: (0, _mockTypeorm.MockTypeORM) is not a constructor
This usually happens in CommonJS environments trying to `require` an ESM-first package, or incorrect import syntax.
fixFor 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. Error: Cannot find module 'sinon'
The `sinon` package is a peer dependency of `mock-typeorm` and must be installed explicitly.
fixInstall Sinon.js and its TypeScript types: `npm install --save-dev sinon @types/sinon`.
ConnectionNotFoundError: Connection "default" was not found.
`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.
fixEnsure 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.
Audit
Dependencies
sinonrequiredRuntime peer dependency for creating mocks and stubs. Mock TypeORM uses Sinon internally, making it framework-agnostic.
typeormrequiredPeer dependency as Mock TypeORM is designed to mock its functionalities. Ensure compatible versions are installed.