Great approach, But if you want a cleaner way to mock without implementing custom functions inside the test, you can mock return values directly using jest.mock().
This makes the setup reusable across multiple tests:
jest.mock('mailgun-js');
import mailgun from 'mailgun-js';
import Mailer from '../../../../server/services/emails/mailer';
mailgun.mockReturnValue({
messages: () => ({
send: jest.fn().mockImplementation((args, callback) => callback())
})
});
Now, the test becomes much simpler:
test('successful email send', async () => {
const result = await Mailer.send('to@example.com', 'Subject', 'Body');
expect(result).toBe('The email was sent successfully!');
});
This approach makes your jest mock class setup much cleaner while keeping the focus on testing. ![]()