Notes Used to Craft this Lesson
If you'll recall, our welcome email is being sent via an event listener.
export default class UserService { /** * Sends a welcome email to the user. * The email is sent asynchronously and will not block the execution of the current code. * @param data - An object containing the user's full name and email address * @returns A promise resolving when the email is sent */ async sendWelcomeEmail(data: { fullName: string | null; email: string }) { await emitter.emit('mail:send_welcome_email', data) } }Copied!
- app
- services
- user_service.ts
What if we also wanted to test the event listener itself?
We only have one listener in our project, so let's create a "listeners" specification for now. You can always split this into a folder with separate specifications per listener, should your number of listeners grow.
node ace make:test listeners --suite=unitCopied!
For this one, we're just going to name the test after the listener itself. Listeners are pretty specific in purpose as-is, so it'll be descriptive enough.
test.group("Listeners", () => { test("SendWelcomeEmail listener", async ({ assert }) => {}); });Copied!
Okay, again, the listener sends an email, so we'll want to fake the mailer, and we can go ahead and add our cleanup as well.
test.group("Listeners", () => { test("SendWelcomeEmail listener", async ({ cleanup }) => { const { mails } = mail.fake(); cleanup(() => mail.restore()); // todo }); });Copied!
Then, we want to instantiate an instance of our event listener and call the method we want to test.
test.group("Listeners", () => { test("SendWelcomeEmail listener", async ({ cleanup }) => { const { mails } = mail.fake(); cleanup(() => mail.restore()); const user = { fullName: "Phillip Fry", email: "phillip.fry@test.com", }; const listener = new SendWelcomeEmail(); await listener.handle(user); }); });Copied!
Finally, we'll make our assertions.
test.group("Listeners", () => { test("SendWelcomeEmail listener", async ({ cleanup }) => { const { mails } = mail.fake(); cleanup(() => mail.restore()); const user = { fullName: "Phillip Fry", email: "phillip.fry@test.com", }; const listener = new SendWelcomeEmail(); await listener.handle(user); mails.assertSentCount(1); mails.assertSent(WelcomeEmailNotification, ({ message }) => { return message.hasTo(user.email); }); }); });Copied!