princelionelnzi's avatar

Test Laravel Notification using PHPUnit

Hello, I am new to PHPUnit and I just made a test to send a notification after a new user is registered.

    /** @test */
    function a_confirmation_email_is_sent_upon_registration()
    {
        Notification::fake();

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

        Notification::assertSentTo(
            [$user],
            \App\Notifications\PleaseConfirmYourEmail::class
        );
    }

When I run the test above, this is the error I get: "Method [getKey] does not exist on Redirect."

When I test it directly with the browser, it works perfectly.

This is how my controller looks like:

    protected function create(array $data)
    {
        return User::forceCreate([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'confirmation_token' => str_limit(md5($data['email'] . str_random()), 25, '')
        ]);
    }

    protected function registered(Request $request, $user)
    {
        $user->notify(new PleaseConfirmYourEmail($user));
    }

Kindly help me fix the error.

Regards.

0 likes
2 replies
dash's avatar

The post()-method returns a response object not an user object.

Try this:

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

        Notification::assertSentTo(
            [\App\User::where('name', 'John')->first()],
            \App\Notifications\PleaseConfirmYourEmail::class
        );
2 likes

Please or to participate in this conversation.