dlan's avatar
Level 3

How to test a job that is dispatching a notification inside?

I don't know if I'm doing it right. I'm fairly new to testing. The test is failing with the following error message Expected [App\Notifications\TaskDueNotification] to be sent 2 times, but was sent 0 times.

public function test_job_was_dispatched()
    {
        Queue::fake([NotifyUserDueTasksJob::class]);
        Notification::fake();

        $users = User::factory()->has(Task::factory(1)->dueToday())->count(2)->create();

        NotifyUserDueTasksJob::dispatch();

        Queue::assertPushed(NotifyUserDueTasksJob::class);

        $users->each(function ($user) {
            Notification::hasSent($user, TaskDueNotification::class);
        });

        Notification::assertSentTimes(TaskDueNotification::class, 2);
    }

This is how the job looks

class NotifyUserDueTasksJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle(): void
    {
        $tasksDueToday = Task::dueToday()->with('user')->get();

        $tasksDueToday->groupBy('user_id')->each(function ($tasks) {
            $user = $tasks->first()->user;

            $user->notify(new TaskDueNotification($user, $tasks));
        });
    }
}
0 likes
1 reply

Please or to participate in this conversation.