Test Phoneix - broadcast channel into controller API - ConnTest/ChannelTest

Hi,

I have a controller (API) which send a broadcast into a specific channel. I try to do a test to be sure the broadcast is correctly send, See below my code:

Controller

defmodule MyApp.MessageSenderController do
  use MyApp.Web, :controller

  def send_message(conn, %{"message" => message}) do
    PandaPhoenix.Endpoint.broadcast_from(self(), "channel:lobby", "topic:msg", %{message: message})
    send_resp(conn, :no_content, "")
  end
end

Test

defmodule MyApp.MessageSenderControllerTest do
  use MyApp.ConnCase

  test "send broadcast received with render success", %{conn: conn} do
     MyApp.Endpoint.subscribe("channel:lobby")

     conn = conn
       |> put_req_header("accept", "application/json")
       |> post("/api/message", %{"message" => "Hello World"})

     :timer.sleep(2000)
     assert_receive %Phoenix.Socket.Broadcast{event: "topic:msg", payload: %{"message" => "Hello World"}}
     MyApp.Endpoint.unsubscribe("channel:lobby")

     assert response(conn, 204)
  end
end

Error

No message matching %Phoenix.Socket.Broadcast{event: "topic:msg", payload: %{"message" => "Hello World"}} after 100ms.
     Process mailbox:
       {#Reference<0.0.1.548>, {204, [{"cache-control", "max-age=0, private, must-revalidate"}, {"x-request-id", "ft62s22sptosv9na2o1nqojn8552prjm"}], ""}}
       {:plug_conn, :sent}

But I received the message into the my tchat, do you know what I did wrong ?

1 Like

Do you have a sample application that reproduces the error? Because the above should work (i.e. I could not spot anything wrong with it).

1 Like

Do you have multiple endpoints? In the controller you’re broadcasting from PandaPhoenix.Endpoint, but in the test you’re subscribing to MyApp.Endpoint.

2 Likes

I will create an example this week…

I changed PandaPhoenix.Endpoint to MyApp.Endpoint to not show my app name :)… I just forgot this one.