Yogesh.galav
Yogesh.galav

Reputation: 285

How to test Laravel notification without notifiable?

We are sending a slack message to our team channel hence not using a notifiable instance. This is how I did it-

Notification::route('slack', env('SLACK_URL'))
    ->notify(new StaffNotification());

And in StaffNotification

public function toSlack() {
    return (new SlackMessage)->content('New Staff Message.');
}

How should I test StaffNotification as all the assert available are accepting the first parameter as notifiable?

Upvotes: 4

Views: 1645

Answers (2)

Oskar Mikael
Oskar Mikael

Reputation: 326

Laravel has added a new assertion for these kind of use cases, called assertSentOnDemand, which you can use if you're not sending the notification to a notifiable class

use Illuminate\Support\Facades\Notification;

class NotificationTest extends TestCase
{
    public function test_notification_sent()
    {
        Notification::fake();

        // test notification
    
        Notification::assertSentOnDemand(StaffNotification::class);
    }
}

Upvotes: 3

Maksim
Maksim

Reputation: 2957

Laravel creates an AnonymousNotifiable behind the scene when you have not a notifiable in your model, and you can use it:

use Illuminate\Notifications\AnonymousNotifiable;
use Illuminate\Support\Facades\Notification;

class NotificationsTest extends TestCase
{
    public function testSend()
    {
        Notification::fake();
        //perform your code
        Notification::assertSentTo(new AnonymousNotifiable(), StaffNotification::class);
    }
}

Upvotes: 7

Related Questions