'How to unit test typeorm getRepository with Jest?

I am using typescript with typeorm and i have an repository like this:

import { EntityRepository, getRepository, createQueryBuilder } from 'typeorm';


@EntityRepository()
export default class Repo {
  async getSomething(): Promise<Result> {
    const schemaQuery = getRepository(SomeModel)
      .createQueryBuilder('sm')
      .select(...)
      .where(...);
      .....

my test file is like this

import * as typeorm from 'typeorm';
import Repo from '../../../../src/repositories/Repo';

describe(
  'test',
  () => {
    let repo: Repo;
    beforeEach(() => {
      repo = new Repo();
    });
    test('getSomething works', async () => {
      jest.spyOn(typeorm, 'getRepository').mockImplementation(() => ({ // typescript wants me to implement all properties of getRepository which i dont want
        createQueryBuilder: jest.fn(),
      }));
        ...
    });
  },
);

how do i mock getRepository directly from typeorm which is still complying to typescript type check?



Solution 1:[1]

I just had this issue, I actually used your code as a base for my solution. Please try this:

    jest.spyOn(typeorm, "getRepository").mockImplementation(() => {
      const original = jest.requireActual("typeorm");
     // You need all functions used in your Query builder  
     return {
        ...original,
        createQueryBuilder: jest.fn().mockImplementation(() => ({
          subQuery: jest.fn().mockReturnThis() as unknown,
          from: jest.fn().mockReturnThis() as unknown,
          where: jest.fn().mockReturnThis() as unknown,
          select: jest.fn().mockReturnThis() as unknown,
          getQuery: jest.fn().mockReturnThis() as unknown,
          setParameter: jest.fn().mockReturnThis() as unknown,
          getMany: jest
            .fn()
            .mockResolvedValue(expected) as unknown,
        })),
      };
    });

Solution 2:[2]

When I try to do this, I get the error below

 TypeError: Cannot redefine property: getRepository
        at Function.defineProperty (<anonymous>)

      64 |     } as unknown as Installation;
      65 |
    > 66 |     jest.spyOn(typeorm, 'getRepository').mockImplementation(() => {
         |          ^
      67 |       const original = jest.requireActual('typeorm');
      68 |       // You need all functions used in your Query builder
      69 |       return {

see my snippet

import * as typeorm from 'typeorm';
.
.
.
    jest.spyOn(typeorm, 'getRepository').mockImplementation(() => {
      const original = jest.requireActual('typeorm');
      // You need all functions used in your Query builder
      return {
        ...original,
        createQueryBuilder: jest.fn().mockImplementation(() => ({
          subQuery: jest.fn().mockReturnThis() as unknown,
          from: jest.fn().mockReturnThis() as unknown,
          where: jest.fn().mockReturnThis() as unknown,
          select: jest.fn().mockReturnThis() as unknown,
          getQuery: jest.fn().mockReturnThis() as unknown,
          setParameter: jest.fn().mockReturnThis() as unknown,
          getMany: jest.fn().mockResolvedValue(expected) as unknown,
        })),
      };
    });

Solution 3:[3]

Had the same issue after updating the jest library, worked around it by mocking the getRepository method directly from the typeorm/globals instead of typeorm(index file)

import * as typeorm_functions from 'typeorm/globals';

jest.spyOn(typeorm_functions, 'getRepository').mockReturnValue({
 createQueryBuilder: jest.fn().mockImplementation(() => ({
      subQuery: jest.fn().mockReturnThis() as unknown,
      from: jest.fn().mockReturnThis() as unknown,
      where: jest.fn().mockReturnThis() as unknown,
      select: jest.fn().mockReturnThis() as unknown,
      getQuery: jest.fn().mockReturnThis() as unknown,
      setParameter: jest.fn().mockReturnThis() as unknown,
      getMany: jest
        .fn()
        .mockResolvedValue(expected) as unknown,
    })),
} as unknown as Repository<unknown>);

Solution 4:[4]

I was experiencing the following error when using the approved solution:

TypeError: Cannot redefine property: getRepository
        at Function.defineProperty (<anonymous>)

In order to resolve this issue, I used the following import statement instead:

import * as typeorm from "typeorm/globals";

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeremy
Solution 2 JohnTheBeloved
Solution 3 Andreea
Solution 4 ahmadibnrachid