3
votes

I am creating a test for Laravel's built-in email verification and am unsure how to test this via PHPUnit. I'm able to receive the notification emails using mailtrap.io but am unable to make the PHPUnit test pass.

Here is my test:

namespace Tests\Feature;

use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;

class RegistrationTest extends TestCase
{
    use RefreshDatabase;

    function test_a_confirmation_email_is_sent_on_registration()
    {
        Notification::fake();

        $user = create('App\User');

        Notification::assertSentTo($user, VerifyEmail::class);
    }
}

I'm looking to have the assertSentTo to pass.

Right now I am getting:

The expected [Illuminate\Auth\Notifications\VerifyEmail] notification was not sent. Failed asserting that false is true. /home/jhiggins/projects/forum/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/NotificationFake.php:52 /home/jhiggins/projects/forum/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:237 /home/jhiggins/projects/forum/tests/Feature/RegistrationTest.php:20

1
You don't need to test if the email is sent. This is already handled by the Laravel Framework given the fact that is a Laravel core feature. What you need to ensure is that the event is dispatched (what you already did). This should be enough to move forward to your next feature ;)Kenny Horna
I understand that this is handled via the framework but shouldn't there still be a way to test the email was sent?James Higgins
You can indeed test custom Mailables or Notifications, but in this particular case you want to test a Laravel framework feature, this is already test it so it wouldn't make sense to re-test it. Of couse you can still do this manually (like you try to do) but make sure to implement in your test the registration flow.Kenny Horna
@HCK Thanks for the clarification, that makes sense to me.James Higgins
I'm upvoting this question because I'm in a position where I'm making a Single Page Application, which requires me to remake the authentication structure. I would like a way to test this notification, but it keeps failing even though i do get the emails. stackoverflow.com/questions/60888256/…good_afternoon

1 Answers

1
votes

When a new user is registered, Laravel (5.7 and above) dispatches a Registered Event, so I think the main point here would be to assert that event has been called. The rest of the work (sending email verification, etc.) is already handled by the Laravel Framework.

Here is a snippet of my feature test:

public function a_confirmation_email_is_sent_upon_registration()
{
    Event::fake();

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

    Event::assertDispatched(Registered::class);
}