Matt Koevort
Matt Koevort

Reputation: 5

Mocking Relationships in TypeOrm + NestJS

I'm having difficulty testing a NestJS service which utilises a simple entity that only has one relationship. The related entity, however, is related to many other entities which in turn are also related to other entities. I don't want to import all of the entities and pass to TypeOrmModule.forRoot, and if I don't I get an error like the following:

Entity metadata for Wallet#customer was not found.

For every entity that has not been imported. Is it possible to "mock" the relationship in some way?

Test:

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

Entity

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

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

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

Upvotes: 0

Views: 1860

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70450

For unit tests, I would suggest not connecting to a live database or using any imports, but instead just using custom providers to mock the dependencies of the service you're testing. This repository has a bunch of examples including some for TypeORM. A very basic setup, based on the imports you have, might be something like

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

Now you can replace walletRepoMock and walletTransactionRepoMock with mock implementation of the methods you use for Repository and you'll be good to go

Upvotes: 1

Related Questions