Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test broadcast driver?

I am wondering if its possible to test ShouldBroadcast in Laravel? My test will trigger the even that implements ShouldBroadcast, however, I've noticed that broadcasting didn't happen.

Of course, the broadcasting event is working in the app it self.

Has any one tried such test?

like image 467
simo Avatar asked Mar 15 '16 11:03

simo


3 Answers

It's an old question, but just in case it can help someone : i did for myself an assert function that you should add to your TestCase.php.

The idea is to set the broadcast driver to "log" and then to read the 4th line from the end to see if it's a broadcast log.

In your phpunit.xml

Add the folowing line to the node:

<env name="BROADCAST_DRIVER" value="log"/>

In your TestCase.php file

Add the folowing function :

public function assertEventIsBroadcasted($eventClassName, $channel=""){
  $logfileFullpath = storage_path("logs/laravel.log");
  $logfile = explode("\n", file_get_contents($logfileFullpath));

  if(count($logfile) > 4){
    $supposedLastEventLogged = $logfile[count($logfile)-5];

    $this->assertContains("Broadcasting [", $supposedLastEventLogged, "No broadcast were found.\n");

    $this->assertContains("Broadcasting [".$eventClassName."]", $supposedLastEventLogged, "A broadcast was found, but not for the classname '".$eventClassName."'.\n");

    if($channel != "")
      $this->assertContains("Broadcasting [".$eventClassName."] on channels [".$channel."]", $supposedLastEventLogged, "The expected broadcast (".$eventClassName.") event was found, but not on the expected channel '".$channel."'.\n");
  }else{
    $this->fail("No informations found in the file log '".$logfileFullpath."'.");
  }
}
like image 110
Adrien C Avatar answered Oct 31 '22 12:10

Adrien C


Instead of checking what's written in log, you can to use the assertion 'expectsEvents', which you can test if a certain event is launched.

public function testMethod(){
   $this->expectsEvents(YourEventClass::class)
    ...your code test...
}

For more info: https://laravel-guide.readthedocs.io/en/latest/mocking/

like image 2
Giuseppe Toto Avatar answered Oct 31 '22 11:10

Giuseppe Toto


with Adrienc solutions with dynamically getting index of last event

private function getIndexOfLoggedEvent(array $logfile)
{
    for ($i = count($logfile) - 1; $i >=0 ; $i--) {
        if (strpos($logfile[$i], 'Broadcasting [Illuminate\Notifications\Events\BroadcastNotificationCreated]') !== false) {
            return $i;
        }
    }
}

which will give you index of the line of last broadcast

like image 1
msonowal Avatar answered Oct 31 '22 12:10

msonowal