我有一个驱动程序频道,可以将其位置广播到供应商频道。
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
这个断言会失败,因为它只检查来自DriverChannel
的广播,如何断言广播到VendorChannel
,我查看了源代码,似乎没有选项通过一个channel_name
到assert_broadcast
宏。
[另一个注意事项]我也有控制器制作的广播,如果我知道答案,我也可以断言那些广播! :)
答案 0 :(得分:6)
assert_broadcast
仅适用于订阅的主题,但您可以直接通过MyApp.Endpoint.subscribe / 2和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
答案 1 :(得分:4)
您需要的新版本self
MyApp.Endpoint.subscribe("vendors:lobby")
MyApp.Endpoint.unsubscribe("vendors:lobby")
如果您没有“取消订阅”,您将收到警告:
[warning] Passing a Pid to Phoenix.PubSub.subscribe is deprecated. Only the calling process may subscribe to topics
新代码:
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