【问题标题】:How to unit test typeorm getRepository with Jest?如何使用 Jest 对 typeorm getRepository 进行单元测试?
【发布时间】:2021-08-08 00:36:21
【问题描述】:

我正在使用带有 typeorm 的 typescript,并且我有一个这样的存储库:

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


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

我的测试文件是这样的

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

我如何直接从仍然符合 typescript 类型检查的 typeorm 模拟 getRepository?

【问题讨论】:

标签: javascript typescript testing jestjs typeorm


【解决方案1】:

我刚刚遇到了这个问题,我实际上使用您的代码作为我的解决方案的基础。请试试这个:

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

【讨论】:

  • 如何模拟其中包含 where 子句的 typeorm getRepository 查找方法?例如:userRepo.find({ where: {"userId": 5} });
  • 您可能需要将getMany 字段替换为一个笑话函数并更改解析值
【解决方案2】:

当我尝试这样做时,我收到以下错误

 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 {

看看我的sn-p

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

【讨论】:

  • 我也有同样的问题=(你找到解决办法了吗?
猜你喜欢
  • 2020-12-30
  • 2020-11-12
  • 2020-12-28
  • 1970-01-01
  • 2019-05-16
  • 1970-01-01
  • 2021-09-16
  • 2017-08-23
  • 1970-01-01
相关资源
最近更新 更多