Ranx99's avatar

How to test a queued notification?

I have a WelcomeNotification which implements ShouldQueue

class WelcomeNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        // send a welcome message to the user via mailtrap
    }

}

How can I test if this notification has been pushed to the queue?

I am trying to test it like this but I am getting The expected [App\Notifications\WelcomeNotification] job was not pushed

    /** @test */
    public function welcome_notification_is_pushed_to_queue()
    {
        Queue::fake();

        $this->post(route('register'), [
            'name' => 'John Doe',
            'email' => '[email protected]',
            'password' => 'passwordtest',
        ]);

        Queue::assertPushed(WelcomeNotification::class);
    }

Inside my registered function in RegisterController:

    protected function registered(Request $request, $user)
    {
          $user->notify(new WelcomeNotification());
          // other code
    }

I have successfully asserted that WelcomeNotification is correctly being sent to the user when registering using Notification::assertSentTo.

My issue is how to test if WelcomeNotification was pushed to the queue or not?

0 likes
2 replies
JohnBraun's avatar

How do you obtain the $user variable in your controller?

protected function registered(Request $request, $user)
{
    $user->notify(new WelcomeNotification());
    // other code
}

Couldn't you better use auth()->user()->notify(new WelcomeNotification()); ?

protected function registered(Request $request)
{
    auth()->user->notify(new WelcomeNotification());
    // other code
}

Please or to participate in this conversation.