Mock TypeORM

1.0.4 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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 } });
  });
});

view raw JSON →