Typeorm Jest mocking
Asked Answered
H

3

7

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?

Hufuf answered 12/5, 2021 at 19:18 Comment(1)
Anything new on that issue?Annunciate
T
8

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');
Tricia answered 15/5, 2021 at 3:18 Comment(1)
Mocking all attributes causes same problem with decorators as I describe at the end. I thought that your solution with returning actual logic would be the answer, but that caused another error somewhere inside typeorm. It looks like my solution best suits my needs.Hufuf
L
1

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', () => {});
});
Lyonnaise answered 16/2, 2022 at 11:57 Comment(0)
E
0

I published a package to npm named Mock TypeORM and it can be utilized with any testing library e.g. Jest, Mocha, Vitest etc. And here is the documentation for this package.

By using this package, you don't need to mock anything. Everything will be setup for you. Definitely try out that package if you are struggling to mock TypeORM with any testing library.

Evanish answered 26/6 at 5:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.