I have a driver channel which broadcasts their location to a vendor channel.
defmodule MyApp.DriverChannel do
#...
def handle_in("transmit", payload, socket) do
MyApp.Endpoint.broadcast! "vendors:lobby", "track", payload
{:noreply, socket}
end
end
defmodule MyApp.DriverChannelTest do
#....
test "location broadcasts to vendors:lobby", %{socket: socket} do
push socket, "transmit", %{"hello" => "all"}
assert_broadcast "track", %{"hello" => "all"}
# Want something like this
# assert_broadcast "vendors:lobby", "track", %{"hello" => "all"}
end
end
This assertion would fail, as it only checks the broadcast from DriverChannel
, how to assert the broadcast made to VendorChannel
, I looked through the source code, it seems like there is no option to pass a channel_name
to assert_broadcast
macro.
[ Another note] I also have broadcast made from controllers, if I know answer to this, I could also assert those broadcasts too! :)
The new version you need self
MyApp.Endpoint.subscribe("vendors:lobby")
MyApp.Endpoint.unsubscribe("vendors:lobby")
if you do not 'unsubscribe' you will have a warning:
[warning] Passing a Pid to Phoenix.PubSub.subscribe is deprecated. Only the calling process may subscribe to topics
new code:
test "location broadcasts to vendors:lobby", %{socket: socket} do
MyApp.Endpoint.subscribe("vendors:lobby")
push socket, "transmit", %{"hello" => "all"}
assert_broadcast "track", %{"hello" => "all"}
assert_receive %Phoenix.Socket.Broadcast{
topic: "vendors:lobby",
event: "track",
payload: %{"hello" => "all"}
MyApp.Endpoint.unsubscribe("vendors:lobby")
end
assert_broadcast
is only for the subscribed topic, but you can subscribe directly via MyApp.Endpoint.subscribe/2 and assert_receive
:
test "location broadcasts to vendors:lobby", %{socket: socket} do
MyApp.Endpoint.subscribe(self, "vendors:lobby")
push socket, "transmit", %{"hello" => "all"}
assert_broadcast "track", %{"hello" => "all"}
assert_receive %Phoenix.Socket.Broadcast{
topic: "vendors:lobby",
event: "track",
payload: %{"hello" => "all"}}
end
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