Typeorm Jest mocking

Viewed 6891

I'm trying to mock one of Typeorm module function in Jest and I want to do it in cleanest possible way. What I managed to create that works:

jest.mock("typeorm", () => ({
    __esModule: true,
    getCustomRepository: jest.fn(),
    PrimaryGeneratedColumn: jest.fn(),
    Column: jest.fn(),
    CreateDateColumn: jest.fn(),
    UpdateDateColumn: jest.fn(),
    Entity: jest.fn(),
    EntityRepository: jest.fn(),
    Repository: jest.fn(),
}));

But I want to mock only getCustomReposity and when I leave mock only for that function:

jest.mock("typeorm", () => ({
    __esModule: true,
    getCustomRepository: jest.fn(),
}));

Tests don't even run, because entity and repository use some decorators and classes from Typeorm. I also tried to generate mocks for whole module:

jest.mock("typeorm", () => jest.createMockFromModule("typeorm"));

I got errors for generated mock decorators:

TypeError: decorator is not a function
    2 |
    3 | @Entity({ name: "users" })
  > 4 | export class User {

Is there an way to create such mock in cleaner way than I did?

2 Answers

Your code requires more than what you mock.

If you mock

jest.mock("typeorm", () => ({
    __esModule: true,
    getCustomRepository: jest.fn(),
}));

Then in you code, import { Entity} from 'typeorm';, now Entiry is undefined. The same for other attributes except getCustomRepository.

You can fix that issue with your first solution, or just mock what you want to mock and return another attribute as actual logic.

jest.mock('typeorm', () => {
  const actual = jest.requireActual('typeorm');
  return {
    ...actual,
    getCustomRepository: jest.fn(),
  }
});

Or mock all attributes of typeorm:

jest.mock('typeorm');

You can also mock getCustomRepository this way:

import typeorm = require('typeorm');

describe('Your test suit', () => {
  beforeAll(() => {
    typeorm.getCustomRepository = jest.fn().mockReturnValue({
      yourMethod: jest.fn(),
    });
  });

  it('your test case', () => {});
});
Related