简体   繁体   中英

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?

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

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

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";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM