0

I am writing a test case for my findAll service method and this is my findAll service. I am using Typeform createQueryBuilder to find my data with pagination. I found many articles and questions but non of are can't understand exactly what is going on. So I really really need your help.

 async findAll(getPaginationParamDto: PaginationParamDto): Promise<GetCcAdminResponseDto> {
    try {
      const result = this.ccAdminRepo
        .createQueryBuilder()
        .leftJoinAndSelect('CcAdmin.userId', 'userId')
        .where({ isArchived: false });
      const total = await result.getCount();
      const totalPages =
        total % getPaginationParamDto.limit === 0
          ? total / getPaginationParamDto.limit
          : Math.floor(total / getPaginationParamDto.limit) + 1;

      const data = await result.offset(getPaginationParamDto.offset).limit(getPaginationParamDto.limit).getMany();
      // Create custom response according to swagger
      const customData = data.map((data) => {
        if (data.userId) {
          const userId = data.userId.userId;
          return {
            ...data,
            userId: userId,
          };
        }
      });
      return {
        total,
        totalPages,
        data: customData,
      };
    } catch (error) {
      console.log(error);
      throw error;
    }
  }

And This is my test case for the service and findAll service method...

describe('CcAdminService', () => {
  let ccAdminService: CcAdminService;
  let sandbox: sinon.SinonSandbox;
  beforeAll(async () => {
    sandbox = sinon.createSandbox();
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        CcAdminService,
        {
          provide: getRepositoryToken(CcAdmin),
          useValue: sinon.createStubInstance(Repository),
        },
      ],
    }).compile();
    ccAdminService = module.get<CcAdminService>(CcAdminService);
  });

  it('should call get all method with expected params', async () => {
    const createQueryBuilder: any = {
      leftJoinAndSelect: () => createQueryBuilder,
      where: () => createQueryBuilder,
    };

    const getPaginationParamDto = new PaginationParamDto();
    const findAllCcAdminSpy = jest.spyOn(ccAdminService, 'findAll');
    await ccAdminService.findAll(getPaginationParamDto);
    expect(findAllCcAdminSpy).toHaveBeenCalledWith(createQueryBuilder);
  });
  afterAll(async () => {
    sandbox.restore();
  });
});

When I run this test I get an error

Cannot read property 'leftJoinAndSelect' of undefined

Can anyone help me with this. Thanks.

Zenixo
  • 727
  • 1
  • 12
  • 36
  • Instead of mocking your repository, I recommend you opt for an in-memory database solution, such as `sqlite`. You could use this question for reference: https://stackoverflow.com/questions/70521273/how-to-unit-test-a-custom-repository-of-typeorm-in-nestjs – Dezzley Aug 12 '22 at 07:57

1 Answers1

0

You need to change this

const createQueryBuilder: any = {
  leftJoinAndSelect: () => createQueryBuilder,
  where: () => createQueryBuilder,
};

to this

  const leftJoinAndSelect = jest.fn();
  const where = jest.fn(() => ({ leftJoinAndSelect }));
  spyRepository.createQueryBuilder = jest.fn(() => ({ where }));

You can check my more detailed answer here

chavy
  • 841
  • 10
  • 20