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

186
Views
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
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!