KarlHill69's avatar

Laravel test failed, why?

I have this test. it's failed. why?


    /** @test */
    public function it_sends_email_notification_to_provider()
    {
        // Fake the Mail facade
        Mail::fake();
        $this->withoutExceptionHandling();

        $post = Post::factory()->published()
            ->create([
                'emails' => '[email protected],[email protected]',
            ]);

        // Dispatch the SendEmailNotificationToProvider job
        SendEmailNotificationToProvider::dispatch($post);

        // Assert that an email was sent to each provider
        Mail::assertSent(PostPublishedInformProvider::class, function ($mail) use ($post) {
            return $mail->assertTo('[email protected]');
        });

        // Optionally, you can check the number of times the email was sent
        Mail::assertSent(PostPublishedInformProvider::class, 2);
    }
0 likes
4 replies
tisuchi's avatar

@karlhill69 can you be more explicit? Provide more context, what error you are getting?

Or provide your implementation if possible.

1 like
KarlHill69's avatar

@tisuchi thanks your query. this is my error:

F 1 / 1 (100%)

Time: 00:01.029, Memory: 56.50 MB

There was 1 failure:

  1. Tests\Feature\ScholarshipTest::it_sends_email_notification_to_provider Did not see expected recipient [provider1@example.com] in email 'to' recipients. Failed asserting that false is true.

this is my implmeentation:

<?php

namespace App\Jobs;

use App\Models\Post;
use App\Mail\PostPublishedInformProvider;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

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

    public function __construct(public Post $post)
    {
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        foreach (explode(',', $this->post->emails) as $email) {
            Mail::to($email)->send(new PostPublishedInformProvider($this->post));
        }
    }
}
tisuchi's avatar
tisuchi
Best Answer
Level 70

@KarlHill69 If I understand you correctly, you are trying to send email to multiple users. Therefore your $mail->assertTo('provider1@example.com');.

I think you can fix your code like this way:

        Mail::assertSent(PostPublishedInformProvider::class, function ($mail) use ($post) {
            return in_array('[email protected]', array_column($mail->to, 'address'));
        });
1 like

Please or to participate in this conversation.