|
| 1 | +/** |
| 2 | + * Module dependencies. |
| 3 | + */ |
| 4 | +import { jest, describe, test, expect, beforeEach } from '@jest/globals'; |
| 5 | + |
| 6 | +// Mock config, files, and providers before importing mailer |
| 7 | +jest.unstable_mockModule('../../../../config/index.js', () => ({ |
| 8 | + default: { |
| 9 | + mailer: { |
| 10 | + provider: 'resend', |
| 11 | + from: 'test@example.com', |
| 12 | + options: { apiKey: 're_test_123' }, |
| 13 | + }, |
| 14 | + }, |
| 15 | +})); |
| 16 | + |
| 17 | +jest.unstable_mockModule('../../files.js', () => ({ |
| 18 | + default: { |
| 19 | + readFile: jest.fn().mockResolvedValue('<p>{{name}}</p>'), |
| 20 | + }, |
| 21 | +})); |
| 22 | + |
| 23 | +const mockSend = jest.fn().mockResolvedValue({ id: 'email_123' }); |
| 24 | +jest.unstable_mockModule('../provider.resend.js', () => ({ |
| 25 | + default: jest.fn().mockImplementation(() => ({ send: mockSend })), |
| 26 | +})); |
| 27 | + |
| 28 | +jest.unstable_mockModule('../provider.nodemailer.js', () => ({ |
| 29 | + default: jest.fn().mockImplementation(() => ({ send: jest.fn() })), |
| 30 | +})); |
| 31 | + |
| 32 | +const { default: mailer } = await import('../index.js'); |
| 33 | + |
| 34 | +describe('mailer index with resend provider unit tests:', () => { |
| 35 | + beforeEach(() => { |
| 36 | + jest.clearAllMocks(); |
| 37 | + }); |
| 38 | + |
| 39 | + test('should report as configured when from is set', () => { |
| 40 | + expect(mailer.isConfigured()).toBe(true); |
| 41 | + }); |
| 42 | + |
| 43 | + test('should send mail using the resend provider', async () => { |
| 44 | + mockSend.mockResolvedValue({ id: 'email_456' }); |
| 45 | + |
| 46 | + const result = await mailer.sendMail({ |
| 47 | + to: 'user@example.com', |
| 48 | + subject: 'Welcome', |
| 49 | + template: 'welcome', |
| 50 | + params: { name: 'Alice' }, |
| 51 | + }); |
| 52 | + |
| 53 | + expect(mockSend).toHaveBeenCalledWith( |
| 54 | + expect.objectContaining({ |
| 55 | + from: 'test@example.com', |
| 56 | + to: 'user@example.com', |
| 57 | + subject: 'Welcome', |
| 58 | + html: '<p>Alice</p>', |
| 59 | + }), |
| 60 | + ); |
| 61 | + expect(result).toEqual({ id: 'email_456' }); |
| 62 | + }); |
| 63 | + |
| 64 | + test('should return null on send error', async () => { |
| 65 | + mockSend.mockRejectedValue(new Error('API failure')); |
| 66 | + |
| 67 | + const result = await mailer.sendMail({ |
| 68 | + to: 'user@example.com', |
| 69 | + subject: 'Test', |
| 70 | + template: 'welcome', |
| 71 | + params: { name: 'Bob' }, |
| 72 | + }); |
| 73 | + |
| 74 | + expect(result).toBeNull(); |
| 75 | + }); |
| 76 | +}); |
0 commit comments