MUM's avatar
Level 4

assertDispatched fails

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?

0 likes
2 replies
MUM's avatar
Level 4

Ah, that makes sense! I had not thought about that! Thanks for the tip! It's working now.

Please or to participate in this conversation.