sr57's avatar
Level 39

Event simple test - How to?

First time I want to test an event and still get the msg "The expected [app\Events\TestEvent] event was not dispatched"

The event : TestEvent.php

class TestEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;

public function __construct()
{
$this->message =  '...';
}


public function broadcastOn(){
    return new Channel('bc1');
}
public function broadcastWith(){
    return ['message' => Str::random(15)];
}

The test : Test1Test.php

    public function test1()
    {
       Event::fake();
       
       event(new \App\Events\TestEvent());
       Event::assertDispatched(TestEvent::class);				# event was not dispatched with or without "use app\Events\TestEvent;"

    }

Test run

   FAIL  Tests\Feature\Test1Test
  ✓ example
  ⨯ 1

  ---

  • Tests\Feature\Test1Test > 1
  The expected [app\Events\TestEvent] event was not dispatched.
  Failed asserting that false is true.

Thanks in advance for any explanation.

0 likes
4 replies
MohamedTammam's avatar
Level 51

Did you try

public function test1()
{
    Event::fake();
       
    TestEvent::dispatch();
    Event::assertDispatched(TestEvent::class);
}
sr57's avatar
Level 39

@mohamedtammam

Class "app\Events\TestEvent" not found

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

use Illuminate\Support\Facades\Event;
use app\Events\TestEvent;

class Test1Test extends TestCase
{	
    public function test1() {
       Event::fake();
       
	   TestEvent::dispatch();
       Event::assertDispatched(TestEvent::class);
    }
}
sr57's avatar
Level 39

@mohamedtammam

OK

use App\Events\TestEvent;

not awake this morning :-) and not the "good/appropriate" error msg with the first syntax

Please or to participate in this conversation.