I'm new to unit testing. I have two modules, one of them testing the other.
getAllEmails.js
(The architecture looks weird, but this resembles the actual code I am working with. Created this just for trial purposes).
import Email from "../models/email.js";
export const one = async() => {
const emails = await getAllEmails();
return emails
}
export const getAllEmails = async() => {
console.log("Getting emails")
const emails = await Email.find({});
return emails
}
getAllEmails.test.js
import { one } from './getAllEmails.js';
import { jest } from "@jest/globals"
jest.mock('./getAllEmails.js', () => {
return {
getAllEmails: jest.fn(() => [{ email: 'email1@example.com' }]),
};
});
test('Function one() returns correct emails', async () => {
const expectedEmails = [
{ email: 'email1@example.com' }
];
const result = await one();
expect(result).toEqual(expectedEmails);
});
From what I understood, the getAllEmails should have been mocked, and so when we call await one()
, it should just have returned [{email: 'email1@example.com'}]. However, running this test gives the error:
Jest did not exit one second after the test run has completed.
'This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
Any help would be much appreciated.