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

374
Vistas
How to mock mongoose model constructor in nestjs

I have a nestjs service that uses mongoose. In a function I wish to test it creates a new model, but I could not find a way to mock that.

I have the following service

@Injectable()
export class ProjectService {

    constructor(
        @InjectModel("Project") private projectModel: Model<ProjectDocument>,
    ) {}

    public dto2ProjectModel(dto: ProjectDto) {
        return new this.projectModel({
            _id: dto.id? Types.ObjectId(dto.id) : Types.ObjectId(),
            name: dto.name.toUpperCase()
        });
    }
}

And I created the test following the documentation like so:

describe('ProjectService tests', () => {
    let projectService: ProjectService;

    beforeEach(async () => {
        const moduleRef = await Test.createTestingModule({
        providers: [
            ProjectService, 
            {
                provide: getModelToken("Project"),
                useValue: {
                    find: jest.fn(),
                    findById: jest.fn()
                }
            }
        ]
        }).compile();
        projectService = moduleRef.get<ProjectService>(ProjectService);
    });

    describe('dto2ProjectModel', () => {
        it('should return a project with the uppercase name', async () => {
            const projectDto: ProjectDto = new ProjectDto();
            projectDto.id = '5a2539b41c574006c46f1a09';
            projectDto.name = 'someName';
            expect(await projectService.dto2ProjectModel(projectDto).name).toEqual('SOMENAME');
        });
    });
});

I tried doing it by example on nestjs documentation and mocking model methods like find is fine, but the new this.projectModel({}) does not work.

Any ideas are greatly appreciated!

over 4 years ago · Santiago Trujillo
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