Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

372
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!