-1

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.

hideme
  • 14
  • 3
  • Does this answer your question? [How to mock functions in the same module using Jest?](https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest) – jonrsharpe Aug 17 '23 at 06:48
  • **TL;DR**: [don't](https://stackoverflow.com/a/70066090/3001761). – jonrsharpe Aug 17 '23 at 06:48

0 Answers0