简体   繁体   English

如何使用 Jest 对 typeorm getRepository 进行单元测试?

[英]How to unit test typeorm getRepository with Jest?

I am using typescript with typeorm and i have an repository like this:我将 typescript 与 typeorm 一起使用,并且我有一个这样的存储库:

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?我如何直接从仍符合 typescript 类型检查的 typeorm 模拟 getRepository?

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)在更新 jest 库后遇到了同样的问题,通过 mocking getRepository 方法直接从 typeorm/globals 而不是 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,
        })),
      };
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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