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?
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."'.");
}
}
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/
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With