【问题标题】:Mocking Relationships in TypeOrm + NestJS在 TypeOrm + NestJS 中模拟关系
【发布时间】:2022-01-02 14:41:40
【问题描述】:

我在测试 NestJS 服务时遇到了困难,该服务使用了一个只有一个关系的简单实体。然而,相关实体与许多其他实体相关,而这些其他实体又与其他实体相关。我不想导入所有实体并传递给TypeOrmModule.forRoot,如果不这样做,我会收到如下错误:

Entity metadata for Wallet#customer was not found.

对于每个尚未导入的实体。是否有可能以某种方式“模拟”这种关系?

测试:

const module: TestingModule = await Test.createTestingModule({
      imports: [
        TypeOrmModule.forRoot(CONNECTION_OPTIONS),
        TypeOrmModule.forFeature([WalletEntity, WalletTransactionEntity]),
      ],
      providers: [WalletService],
    }).compile();

实体

@Entity('wallet')
export class WalletEntity extends BaseEntity {
  @Column()
  customerId: string;

  @OneToOne(() => CustomerEntity, (customer) => customer.wallet)
  customer: CustomerEntity;

  @OneToMany(() => WalletTransactionEntity, (transaction) => transaction.wallet)
  transactions: WalletTransactionEntity[];
}

【问题讨论】:

    标签: jestjs nestjs typeorm


    【解决方案1】:

    对于单元测试,我建议不要连接到实时数据库或使用任何imports,而只是使用自定义提供程序来模拟您正在测试的服务的依赖关系。 This repository 有很多例子,包括一些用于 TypeORM 的例子。根据您的导入,一个非常基本的设置可能类似于

    beforeEach(async () => {
      const modRef = await Test.createTestingModule({
        providers: [
          WalletService,
          {
            provide: getRepositoryToken(WalletEntity),
            useValue: walletRepoMock,
          },
          {
            provide: getRepositoryToken(WalletTransactionEntity),
            useValue: walletTransactionRepoMock,
          }
        ]
      }).compile();
    });
    

    现在您可以将 walletRepoMockwalletTransactionRepoMock 替换为您用于 Repository 的方法的模拟实现,这样就可以了

    【讨论】:

    • 我最终走上了这条路,谢谢你的帮助杰!
    猜你喜欢
    • 2020-04-19
    • 1970-01-01
    • 2021-12-08
    • 2021-03-06
    • 2020-09-01
    • 1970-01-01
    • 2019-10-22
    • 2021-03-05
    • 2020-03-21
    相关资源
    最近更新 更多