Skip to content

Commit

Permalink
Test handle method of an event listener
Browse files Browse the repository at this point in the history
  • Loading branch information
unclexo committed Jan 16, 2023
1 parent ac66840 commit 5b9c220
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
16 changes: 14 additions & 2 deletions app/Listeners/LoginListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,22 @@ public function __construct()
* Handle the event.
*
* @param \Illuminate\Auth\Events\Login $event
* @return void
* @return mixed
*/
public function handle(Login $event)
{
logger("Logged in user: {$event->user->email}");
// Do your stuff

// logger("Logged in user: {$event->user->email}");

// For testing purpose only, in this case.
$this->doSomething();

// For testing purpose only, in this case.
return $event;
}

public function doSomething()
{
}
}
38 changes: 38 additions & 0 deletions tests/Unit/ListenerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Tests\Unit;


use App\Listeners\LoginListener;
use App\Models\User;
use Illuminate\Auth\Events\Login;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ListenerTest extends TestCase
{
use RefreshDatabase;

/** @test */
public function handle_method_of_an_event_listener()
{
$user = User::factory()->create();

$login = new Login('web', $user, false);

$listener = $this->mock(LoginListener::class)->makePartial();

$listener->shouldReceive('doSomething')
->once()
->andReturnNull();

// Say, the handle() method is being called by the event API
$loginEvent = $listener->handle($login);

$this->assertSame('web', $loginEvent->guard);

$this->assertFalse($loginEvent->remember);

$this->assertSame($user->email, $loginEvent->user->email);
}
}

0 comments on commit 5b9c220

Please sign in to comment.