Summer Sale! All accounts are 50% off this week.

devhobby's avatar

Testing laravel email sent

Hi everyone.

I have this email notification code. How to test this?

class FooNotification extends Notification
{
    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new FooEmail())
            ->to($notifiable->routes['mail']);
    }
}
class FooEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this
            ->subject("Subject")
            ->markdown('mail.foo');
    }
}

mail/foo.blade.php

Foo
0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@devhobby You can try this:

    /** @test */
    public function it_sends_notification()
    {
        // Arrange
        Notification::fake();

        // Put your job dispatcher code here

        // Assert
        $this->assertEmailNotificationSentTo('[email protected]', FooNotification::class, function ($notification, $notifiable) {
            $mail = $notification->toMail($notifiable);

            // Ensure that email subject is correct
            $this->assertSame("Subject", $mail->build()->subject);
            $mail->assertSeeInText("Foo");

            return true;
        });
    }

⚠️ Not tested. You may need to adjust!

Check more: https://laravel.com/docs/10.x/notifications#testing

1 like

Please or to participate in this conversation.