【问题标题】:Typeorm Jest mockingTypeorm Jest 嘲讽
【发布时间】:2022-02-16 19:57:54
【问题描述】:

我正在尝试在 Jest 中模拟一个 Typeorm 模块功能,并且我想以最简洁的方式进行。我设法创造出的作品:

jest.mock("typeorm", () => ({
    __esModule: true,
    getCustomRepository: jest.fn(),
    PrimaryGeneratedColumn: jest.fn(),
    Column: jest.fn(),
    CreateDateColumn: jest.fn(),
    UpdateDateColumn: jest.fn(),
    Entity: jest.fn(),
    EntityRepository: jest.fn(),
    Repository: jest.fn(),
}));

但我只想模拟 getCustomReposity 并且当我只为该功能离开模拟时:

jest.mock("typeorm", () => ({
    __esModule: true,
    getCustomRepository: jest.fn(),
}));

测试甚至不运行,因为实体和存储库使用了一些来自 Typeorm 的装饰器和类。我还尝试为整个模块生成模拟:

jest.mock("typeorm", () => jest.createMockFromModule("typeorm"));

生成的模拟装饰器出现错误:

TypeError: decorator is not a function
    2 |
    3 | @Entity({ name: "users" })
  > 4 | export class User {

有没有办法以比我更干净的方式创建这样的模拟?

【问题讨论】:

  • 关于这个问题有什么新的吗?

标签: typescript unit-testing jestjs typeorm ts-jest


【解决方案1】:

您的代码需要的不仅仅是您模拟的内容。

如果你嘲笑

jest.mock("typeorm", () => ({
    __esModule: true,
    getCustomRepository: jest.fn(),
}));

然后在您的代码中,import { Entity} from 'typeorm';,现在 Entiry 未定义。除了getCustomRepository 之外的其他属性也一样。

你可以用你的第一个解决方案来解决这个问题,或者只是模拟你想模拟的东西并返回另一个属性作为实际逻辑。

jest.mock('typeorm', () => {
  const actual = jest.requireActual('typeorm');
  return {
    ...actual,
    getCustomRepository: jest.fn(),
  }
});

或者模拟typeorm的所有属性:

jest.mock('typeorm');

【讨论】:

  • 模拟所有属性会导致与我在最后描述的装饰器相同的问题。我认为您返回实际逻辑的解决方案将是答案,但这会在 typeorm 内部某处引起另一个错误。看起来我的解决方案最适合我的需求。
【解决方案2】:

你也可以这样模拟getCustomRepository

import typeorm = require('typeorm');

describe('Your test suit', () => {
  beforeAll(() => {
    typeorm.getCustomRepository = jest.fn().mockReturnValue({
      yourMethod: jest.fn(),
    });
  });

  it('your test case', () => {});
});

【讨论】:

    猜你喜欢
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2016-02-22
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多