最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to unit test typeorm getRepository with Jest? - Stack Overflow

programmeradmin3浏览0评论

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 plying to typescript type check?

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 plying to typescript type check?

Share Improve this question asked May 18, 2021 at 18:16 Nguyễn Hoàng HưngNguyễn Hoàng Hưng 932 silver badges10 bronze badges 1
  • I have similar questions to test the custom repositories, stackoverflow./questions/67580233/… – Hantsy Commented May 19, 2021 at 14:13
Add a ment  | 

4 Answers 4

Reset to default 6

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

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

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

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,
        })),
      };
    });
发布评论

评论列表(0)

  1. 暂无评论