代码之家  ›  专栏  ›  技术社区  ›  Aleksei Matiushkin

测试客户端通道是否接收到消息

  •  5
  • Aleksei Matiushkin  · 技术社区  · 8 年前

    在我的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)只能为已与push-ref连接的套接字生成套接字引用。

    我肯定广播确实触发了 dev 和 test 具有的环境 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
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Kociamber    8 年前

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

    assert_receive ^expected_payload
    

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

        2
  •  0
  •   script    8 年前

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

     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