【问题标题】:Test that the client channel receives a message测试客户端通道是否收到消息
【发布时间】:2018-05-27 02:26:47
【问题描述】:

在我的 Phoenix 应用程序中,我有一个被MyApp.Endpoint.broadcast(topic, type, data) 污染的频道。这个广播是由一些外部源事件触发的(在我的例子中是 RabbitMQ。)

场景是:MQ 客户端收到一条消息⇒ 应用程序将它广播给特定频道的所有订阅者。我在测试中使用本地本地 RabbitMQ 服务器。

我将如何测试它? Phoenix.ChannelTest.assert_broadcast/3 不能说“进程邮箱是空的。”

assert_reply 需要一个引用并且被称为assert_reply Phoenix.Channel.socket_ref(socket), ... 不能正常工作,引发 “(ArgumentError) 套接字引用只能为与推送引用连接的套接字生成”。 em>

我很肯定广播确实在触发(在devtest 环境中使用wsta 进行检查。)

所以,我的问题是:如何在 Phoenix 测试套件中测试由某些外部源触发的广播事件?


当我尝试从测试进程订阅相应的频道时,正如@Kociamber 所建议的那样,它以同样的方式失败,“进程邮箱为空。”,

test "handle RabbitMQ message", %{socket: _socket} do
  Phoenix.PubSub.subscribe MyApp.PubSub, "channel:topic"
  payload = %{foo: "bar"}
  RabbitMQ.trigger!(payload)
  assert_receive ^payload, 3_000
end

【问题讨论】:

  • 猜猜看:你试过增加assert_broadcast的超时时间吗?
  • @Dogbert 当然,现在是5_000 :) 那是我的第一次尝试。

标签: websocket elixir integration-testing phoenix-framework


【解决方案1】:

我发现以下方法对频道(和广播)测试很有用,看起来它也应该适用于您。首先,您需要使用Phoenix.PubSub.subscribe/2 订阅您的主题,定义您的预期消息(有效负载)值,然后使用assert_receive/2 对其进行测试:

assert_receive ^expected_payload

您可能还想在使用Phoenix.PubSub.unsubscribe/2 完成测试后取消订阅该主题

【讨论】:

  • 毕竟:这是一个完美的解决方案,我很傻 :) 我搞砸了主题名称,这是它不起作用的唯一原因。
  • 很高兴能帮上忙。事实上,错误的话题是我唯一能想到的;)
【解决方案2】:

这是向频道成员广播消息的测试,这可能会对您有所帮助

 test "new_msg event broadcasts new message to other channel members",
  %{socket1: socket1, user1: user1, group: group} do
     {:ok, _, socket1} = subscribe_and_join(socket1, "groups:#
    {group.slug}")

   @endpoint.subscribe("groups:#{group.slug}")

   ref = push socket1, "new_msg", %{text_content: "Hello, World!"}
   assert_reply ref, :ok

   assert_broadcast "new_msg", data

   assert data.user_id == user1.id
   assert data.text_content == "Hello, World!"
 end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-21
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2020-02-01
    相关资源
    最近更新 更多