How to Test Mail Notifications in Laravel ?

Vivek Dhumal
Jun 17, 2018 · 2 min read
<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Notifications\OrderShipped;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ExampleTest extends TestCase
{
public function testOrderShipping()
{
Notification::fake();

// Perform order shipping...

Notification::assertSentTo(
$user,
OrderShipped::class,
function ($notification, $channels) use ($order) {
return $notification->order->id === $order->id;
}
);
}
}
<?phpnamespace Tests\Feature;use Tests\TestCase;
use App\Notifications\OrderShipped;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class ExampleTest extends TestCase
{
public function testOrderShipping()
{
Notification::fake();
// Perform order shipping... Notification::assertSentTo(
$user,
OrderShipped::class,
function ($notification, $channels) use ($order, $user){
// retrive the mail content
$mailData = $notification->toMail($user)->toArray();
$this->assertEquals("Order #{$order->orderNumber} shipped", $mailData['subject']);
$this->assertEquals("Hello {$user->name}!", $mailData['greeting']);
$this->assertContains("Your order #{$order->orderNumber} has been shipped", $mailData['introLines']);
$this->assertEquals("View Order", $mailData['actionText']);
$this->assertEquals(route('orders.show', $order), $mailData['actionUrl']);
$this->assertContains("Thank You!", $mailData['outroLines']);
return $notification->order->id === $order->id;
}
);
}
}

Vivek Dhumal

Written by

Software Developer | https://vivekdhumal.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade