You are also faking the Model event because you did not scope the fake to TenderCreated class only:
Event::fake([
\App\Events\TenderCreated::class
]);
https://laravel.com/docs/8.x/mocking#faking-a-subset-of-events
I currently have the scenario that when a new record is created at "Tender", the Observer responds to this and then fires an event. On the event I currently have a listener that should do something. So far this also works. Now I wanted to cover all this with a test and fail here because Event::assertDispatched thinks that the defined event is not called. If I remove Event::fake, Event:assertDispatched fails and says that the method assertDispatched is missing:
BadMethodCallException: Method Illuminate\Events\Dispatcher::assertDispatched does not exist.
With Event::fake then comes this:
The expected [App\Events\TenderCreated] event was not dispatched.
My test:
<?php
namespace Tests\Feature\App\Events;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
class TenderCreatedTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
}
public function test_event_is_triggered()
{
Event::fake();
$tender = \App\Models\Tender::factory()
->create([
'customer_id' => 1
]);
Event::assertDispatched(\App\Events\TenderCreated::class);
}
}
Inside EventServiceProvider i've defined following listener:
\App\Events\TenderCreated::class => [
\App\Listeners\TenderAllocation::class
]
and following observer:
\App\Models\Tender::observe(\App\Observers\TenderObserver::class);
The TenderObserver contains following code:
<?php
namespace App\Observers;
class TenderObserver
{
public function created(\App\Models\Tender $tender)
{
event(new \App\Events\TenderCreated($tender));
}
}
The TenderAllocation Listener contains that code:
<?php
namespace App\Listeners\Partner;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class TenderAllocation
{
public function __construct()
{
//
}
public function handle(\App\Events\TenderCreated $tender)
{
var_dump('Tender allocation');
}
}
Somehow this does not seem logical to me. What am I doing wrong?
You are also faking the Model event because you did not scope the fake to TenderCreated class only:
Event::fake([
\App\Events\TenderCreated::class
]);
https://laravel.com/docs/8.x/mocking#faking-a-subset-of-events
Please or to participate in this conversation.