PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Qual seria uma maneira adequada de testar os métodos de encadeamento QueryBuilder do TypeORM?


você pode usar jest.spyOn para o QueryBuilder protótipo assim:
import { QueryBuilder } from 'typeorm';

describe('Name of the group', () => {
    it('should do something', () => {
      const queryBuilder: any = {
        into: jest.fn().mockReturnThis(),
        values: jest.fn().mockReturnThis(),
        onConflict: jest.fn().mockReturnThis(),
        setParameter: jest.fn().mockReturnThis(),
        execute: jest.fn().mockRejectedValueOnce(new Error('db Error')),
        // execute: jest.fn().mockResolvedValueOnce({ res: 'mockRes' }),
      };
      jest
        .spyOn(QueryBuilder.prototype, 'insert')
        .mockReturnValueOnce(queryBuilder);
    });
});

uso da função

export async function doQuery(input: any){
  const queryRunner = await Entity.createQueryRunner();
  await queryRunner.manager
  .createQueryBuilder()
  .insert()
  .into(Entity)
  .values(input)
  .onConflict(
    `("id") DO UPDATE SET "date" = :date`
  )
  .setParameter('date', date)
  .execute();
}