How to Test Laravel Real-Time Code Without Opening a Socket
Raheel Shan
December 4th, 2026 · 9 min read
Most of a real-time feature is plain Laravel. You can test all of it with PHPUnit and no connection to anything.
The hub's job is delivery. Your job is the decisions around delivery: who may join, who may post, what gets saved, who gets told. Those decisions are PHP, and they are where the bugs are.
What to test, and what to leave alone
- Test: the token route and its
channelslist, the post route, the presence lookup, the webhook listener - Leave to the package: the webhook signature and timestamp checks (the package has its own tests)
- Leave to the hub: delivery, reconnects, rate limits
One gap remains. Nothing in PHPUnit proves that a message crosses the hub. A manual two-tab check before each release covers it.
The seam that makes it testable
Article 12 put the hub behind an interface. That interface is the test seam:
class FakeTransport implements RealtimeTransport
{
public array $channelSends = [];
public array $userSends = [];
public ?Throwable $failWith = null;
public function toChannel(string $channel, string $event, array $payload): void
{
if ($this->failWith) throw $this->failWith;
$this->channelSends[] = compact('channel', 'event', 'payload');
}
public function toUsers(array $userIds, string $event, array $payload): void
{
$this->userSends[] = compact('userIds', 'event', 'payload');
}
}
Bind it before each test:
protected function setUp(): void
{
parent::setUp();
$this->transport = new FakeTransport();
$this->app->instance(RealtimeTransport::class, $this->transport);
}
private function roomWithMembers(int $count): array
{
$room = Room::create(['name' => 'General']);
$users = User::factory()->count($count)->create();
$room->members()->attach($users->pluck('id'));
return [$room, ...$users->all()];
}
The post route now runs for real against the test database, and instead of calling the hub it records what it would have sent.
Test 1: a member's post is saved and broadcast to the room
public function test_a_member_post_is_saved_and_broadcast(): void
{
[$room, $ann] = $this->roomWithMembers(2);
$this->actingAs($ann)
->postJson("/rooms/{$room->id}/messages", ['text' => 'hello'])
->assertOk();
$this->assertDatabaseHas('room_messages', [
'room_id' => $room->id,
'user_id' => $ann->id,
'text' => 'hello',
]);
$this->assertCount(1, $this->transport->channelSends);
$this->assertSame("room.{$room->id}", $this->transport->channelSends[0]['channel']);
$this->assertSame('room.message', $this->transport->channelSends[0]['event']);
}
The assertion that matters is the channel name. A typo there sends the message to a room nobody joined.
Test 2: a stranger's post goes nowhere
This is the security test from article 9, written as code:
public function test_a_non_member_cannot_post(): void
{
[$room] = $this->roomWithMembers(2);
$outsider = User::factory()->create();
$this->actingAs($outsider)
->postJson("/rooms/{$room->id}/messages", ['text' => 'let me in'])
->assertForbidden();
$this->assertDatabaseCount('room_messages', 0);
$this->assertSame([], $this->transport->channelSends);
}
Test 3: a failed broadcast loses nothing
public function test_a_failed_broadcast_still_saves_the_message(): void
{
[$room, $ann] = $this->roomWithMembers(2);
$this->transport->failWith = new RealtimeHubException('hub down', 0);
$this->actingAs($ann)
->postJson("/rooms/{$room->id}/messages", ['text' => 'saved anyway'])
->assertOk();
$this->assertDatabaseHas('room_messages', ['text' => 'saved anyway']);
}
The user sees success, and the history route fills the gap for everyone else.
Test 4: the token lists exactly the user's rooms
public function test_the_token_lists_only_the_users_rooms(): void
{
Http::fake([
'*/api/token' => Http::response([
'token' => 'abc',
'expiresAtUtc' => now()->addHour()->toIso8601String(),
]),
]);
[$mine, $ann] = $this->roomWithMembers(1);
Room::create(['name' => 'Not mine']);
$this->actingAs($ann)->getJson('/hub-token?user_id=999')->assertOk();
Http::assertSent(fn ($request) =>
$request['userId'] === (string) $ann->id
&& $request['channels'] === ["room.{$mine->id}"]
&& $request->hasHeader('Authorization', 'Bearer '.config('hub.secret')));
}
public function test_a_user_with_no_rooms_still_sends_an_empty_list(): void
{
Http::fake(['*/api/token' => Http::response(['token' => 'abc', 'expiresAtUtc' => now()->addHour()->toIso8601String()])]);
$this->actingAs(User::factory()->create())->getJson('/hub-token')->assertOk();
Http::assertSent(fn ($request) =>
array_key_exists('channels', $request->data()) && $request['channels'] === []);
}
public function test_a_guest_cannot_get_a_token(): void
{
$this->getJson('/hub-token')->assertUnauthorized();
}
The second test pins the rule from article 9: the channels key is always present, because a missing key puts the app in open mode. The query string user_id=999 in the first is the attack, and the test proves the route ignores it.
Test 5: the presence lookup
The browser gets presence from the hub, so your app only asks for it when it decides who needs a push. Fake the facade and test that decision:
public function test_only_members_outside_the_room_get_a_push(): void
{
[$room, $ann, $bob] = $this->roomWithMembers(2);
RealtimeHub::shouldReceive('presence')
->once()
->with("room.{$room->id}")
->andReturn(['channel' => "room.{$room->id}", 'count' => 1, 'users' => [(string) $bob->id]]);
Notification::fake();
(new NotifyOfflineMembers($room, $this->message))->handle();
Notification::assertSentTo($ann, NewRoomMessage::class);
Notification::assertNotSentTo($bob, NewRoomMessage::class);
}
NotifyOfflineMembers is the job from article 10, with the RealtimeHub::presence() call and the whereNotIn query inside it. The hub returns ids as strings, which is why the test passes (string) $bob->id.
Test 6: the one-to-one webhook listener is idempotent
The package's event class has a public constructor, so you can fire an event without the hub:
public function test_a_redelivered_event_is_saved_once(): void
{
$event = new RealtimeEventReceived(
eventId: 'evt-1', appId: 'app', from: '1', to: '2',
eventName: 'chat', payload: ['text' => 'hi'], payloadJson: '{"text":"hi"}',
sentAt: new DateTimeImmutable(), streamId: '1-0',
);
Event::dispatch($event);
Event::dispatch($event);
$this->assertDatabaseCount('messages', 1);
}
To test the route itself end to end, the package README shows how to sign a request with your secret and post it, which exercises the signature check too.
Test 7: the transport maps to the right calls
public function test_the_hub_transport_broadcasts_to_the_channel(): void
{
RealtimeHub::shouldReceive('broadcast')->once()->with('room.5', 'room.message', ['x' => 1]);
(new HubTransport())->toChannel('room.5', 'room.message', ['x' => 1]);
}
public function test_the_hub_transport_sends_users_in_chunks_of_fifty(): void
{
RealtimeHub::shouldReceive('send')->times(3);
(new HubTransport())->toUsers(range(1, 120), 'notice', ['x' => 1]);
}
RealtimeHub::shouldReceive works because the package ships a standard Laravel facade. The 120 ids split into 50, 50 and 20.
What a test cannot tell you
- Whether the hub delivered the message
- Whether your webhook URL is reachable from the hub
- Whether a token has expired on a real connection
- Whether a user who is not in the channel really receives nothing
- How the app behaves when a phone loses signal
Cover those with one manual check before each release:
- Open two browsers as two different users in one room
- Post from each and confirm both receive, and that typing shows on the other side
- Close one, post, reopen it, and confirm
loadMissed()fills the gap - Open a third browser as a non-member, try to join the channel, and confirm it is refused and receives nothing
It takes five minutes, and it is the only test that touches the hub.
The rule
Test the decisions in PHP and check the delivery by hand. The decisions are where a bug costs you data, and delivery is the part the hub owns.
Try it: realtimehub.raheelshan.com/docs
Previous: How to Leave a Hosted Hub for Laravel Reverb in One Afternoon
Next: What It Takes to Run a Real-Time Hub (So You Do Not Have To)
Comment "TESTED" and I'll send you the whole test file.
Found this useful?
Support the work that goes into these posts.