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.