Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
How can I test the function called inside another function in Nestjs?

i am writing test functions in nestjs and i am new to this task.

I mostly had problems with typeorm. but my current problem is that I do not call the paginate function in the PaginateLib class inside the function I wrote in the service. I tested the userList function directly before, but it gave paginate undefined error. Now I used mock and paginate function in test. it still gives undefined error.

Here's my admin.service code

  public async userList(page, limit): Promise<any> {
    const opt = {
      relations: ['userInfo'],
    };
    const userData = await this.paginateLib.paginate(
      getRepository(Users),
      opt,
      page,
      limit,
    );
    return userData;
  }

Here's Paginate function code in PaginateLib class. I'm cutting this short as I don't think it's very necessary.

export class PaginateLib {
  async paginate(repo, opt, page, limit) {
    try {
      page = Number(page);
      limit = Number(limit);
      const items = (Number(page) - 1) * Number(limit);

      const [data, count] = await repo.findAndCount({
        ...opt,
        skip: Number(items),
        take: Number(limit),
      });
      if (count <= items) {
        return [];
      }

and here's my test code

class PaginateMock {
  paginate(repo: any, opt: any, page: number, limit: number) {
    return [];
  }
}

describe('AdminService', () => {
  let service: AdminService;
  let connection: Connection;
  let module: TestingModule;
  let services: PaginateLib;

  beforeAll(async () => {
    const ApiServiceProvider = {
        provide: PaginateLib,
        useClass: PaginateMock,
      },
      module = await Test.createTestingModule({
        imports: [
          TypeOrmModule.forRoot({
            type: '****',
            host: '****',
            port: ****,
            username: '****',
            password: '****',
            database: '****',
            entities: [__dirname + '/../../**/*.entity.ts'],
            synchronize: true,
          }),
        ],
        providers: [
          AdminService,
          ApiServiceProvider,
        ],
      }).compile();

    service = module.get<AdminService>(AdminService);
    services = module.get<PaginateLib>(PaginateLib);
  });

  // afterAll(async () => {
  //   await module.close();
  // });

  describe('User Info', () => {
    it('should be get user list', async () => {   
      const paginateSpy = jest.spyOn(services, 'paginate');
      expect(paginateSpy).toHaveBeenCalled();
      expect(true).toBe(service.userList(1, 1));
    });
});
});

I tried different things many times. but the error I get is undefined. what should I do? Is there anyone have an idea?thank you

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try this:

describe('User Info', () => {
    it('should be get user list', async () => {   
      const paginateSpy = jest.spyOn(services, 'paginate');
      const userData = await service.userList(1, 1);
      expect(paginateSpy).toHaveBeenCalled();
      expect(userData).toBe(); // Don't know what userData actually looks like. So this is up to you
    });
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda