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

188
Vistas
Test function containing mongoose model with Jest

This is the function I want to test:

export const getUser = async (userId: string) => {

  if(!ObjectId.isValid(userId)) {
    return null;
  }

  const getUser = await userModel.findById(userId);

  return getUser;
}

And this is the test I'm trying to run:

import { getUser } from "../controllers/users/user.controller";
import { userModel } from "../db/mongodb";


jest.mock('../db/mongodb')

const userModel = {
    findById: jest.fn()
}


describe('getUser', () => {

    jest.mock('../db/mongodb')
    const expectedOutput = {
        _id: "61642e8d4b817fe1e83758b7",
        first_name: "John",
        last_name: "Doe",
        email: "john.doe@example.com"
    }


    it('should return user if valid ObjectId that exists', async () => {
        const existingId = "61642e8d4b817fe1e83758b7";
        userModel.findById.mockResolvedValue(expectedOutput);

        
        expect(getUser(existingId)).resolves.toBe(expectedOutput);
    });
}

The test fails saying that I received "undefined". What is wrong with the way I mock the userModel.findById() call?

Also it throws the following error:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From src/__tests__/user.controller.test.ts.
about 4 years ago · Juan Pablo Isaza
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