diff --git a/src/fake_mailer.ts b/src/fake_mailer.ts index c6cb782..a7ad72c 100644 --- a/src/fake_mailer.ts +++ b/src/fake_mailer.ts @@ -527,9 +527,16 @@ class MessagesCollection { export class FakeMailer extends Mailer implements MailerContract { mails = new MailsCollection() messages = new MessagesCollection() + #onDispose?: () => void - constructor(name: string, emitter: EmitterLike, config: MailerConfig) { + constructor( + name: string, + emitter: EmitterLike, + config: MailerConfig, + onDispose?: () => void + ) { super(name, new JSONTransport(), emitter, config) + this.#onDispose = onDispose super.setMessenger({ queue: async (mail, sendConfig) => { return this.sendCompiled(mail, sendConfig) @@ -585,6 +592,10 @@ export class FakeMailer extends Mailer implements MailerContract< }, config) } + [Symbol.dispose]() { + this.#onDispose?.() + } + async close() { this.messages.clear() this.mails.clear() diff --git a/src/mail_manager.ts b/src/mail_manager.ts index fd8ba4b..a22b7a3 100644 --- a/src/mail_manager.ts +++ b/src/mail_manager.ts @@ -148,7 +148,7 @@ export class MailManager this.restore()) return this.#fakeMailer } diff --git a/tests/integration/mail_manager.spec.ts b/tests/integration/mail_manager.spec.ts index e17a37a..b2572ec 100644 --- a/tests/integration/mail_manager.spec.ts +++ b/tests/integration/mail_manager.spec.ts @@ -296,6 +296,36 @@ test.group('Mail manager', () => { assert.lengthOf(messages.sent(), 0) }) + test('restore fake mailer using Symbol.dispose', async ({ assert }) => { + const emitter = new Emitter(app) + + const mail = new MailManager(emitter, { + mailers: { + mailer1: () => new JSONTransport(), + }, + }) + + let messages: ReturnType['messages'] + + { + using fake = mail.fake() + await mail.use('mailer1').send((message) => { + message.to('foo@bar.com') + message.subject('Verify email address') + }) + + fake.messages.assertSent({ subject: 'Verify email address' }) + assert.lengthOf(fake.messages.sent(), 1) + messages = fake.messages + } + + /** + * After the block, the fake mailer should be disposed + * and messages should be cleared + */ + assert.lengthOf(messages!.sent(), 0) + }) + test('close all mailers and remove from cache', async ({ assert }) => { const emitter = new Emitter(app) const smtpTransport = new SMTPTransport({