Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Test that the client channel receives a message

In my Phoenix application, I have a channel that is polluted with MyApp.Endpoint.broadcast(topic, type, data). This broadcast is triggered by some external source events (in my case it’s RabbitMQ.)

The scenario is: MQ client receives a message ⇒ the application broadcasts it to all subscribers of the specific channel. I use the native local RabbitMQ server in tests.

How would I test it? Phoenix.ChannelTest.assert_broadcast/3 does not work saying “The process mailbox is empty.”.

assert_reply requires a reference and being called as assert_reply Phoenix.Channel.socket_ref(socket), ... is not working as well, raising “(ArgumentError) Socket refs can only be generated for a socket that has joined with a push ref”.

I am positive the broadcast is indeed triggering (checked in both dev and test environments with wsta.)

So, my question would be: how do I test the broadcast event triggered by some external source within Phoenix test suite?


When I have tried to subscribe to the respective channel from test process, as suggested by @Kociamber, it fails the same way with “The process mailbox is empty.”,

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

Upvotes: 5

Views: 1601

Answers (2)

Kociamber
Kociamber

Reputation: 1155

I've found following way useful for channel (and broadcast) testing, it looks like it should work for you as well. First you need to subscribe to your topic with Phoenix.PubSub.subscribe/2, define your expected message (payload) value and then use assert_receive/2 to test against it:

assert_receive ^expected_payload

You may also want to unsubscribe from the topic after your test is done with Phoenix.PubSub.unsubscribe/2

Upvotes: 3

script
script

Reputation: 2167

This is the test for broadcasting message to channel members this might help you

 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

Upvotes: 0

Related Questions