如何测试或序列化 Phoenix.Socket.Broadcast 负载中的结构?

How to test or serialize struct in Phoenix.Socket.Broadcast payload?

如何在通道测试中自动将 ecto 结构序列化为 json 响应?正如我在 documentation The event’s message must be a serializable map, I found in and in tutorial 中看到的那样,当我在模型中使用 Poison.Encoder 时,应该对通过传输(据我了解)层传递的任何消息进行编码。

示例模型:

use PhoenixTrello.Web, :model
  # ...

  @derive {Poison.Encoder, only: [:id, :first_name, :last_name, :email]}

  # ...
end

从频道功能之一广播:

broadcast_from! socket, "card:created", %{card: card}

终于在测试中尝试从广播接收负载:

assert_receive %Phoenix.Socket.Broadcast{topic: ^t1, event: "card:created", payload: ^payload}

然后它出现不匹配错误,有效负载中没有序列化结构(我试图只匹配派生模型文件):

Process mailbox:
  %Phoenix.Socket.Broadcast{event: "card:created", payload: %{card: %PhoenixTrello.Card{__meta__: #Ecto.Schema.Metadata<:loaded, "cards">, ... user: #Ecto.Association.NotLoaded<association :user is not loaded>, user_id: 1833}}, topic: "boards:1833"}

如何在测试中获取序列化 json 消息,就好像它是客户端应用程序一样?

我会先 assert_receive 原始消息,然后 Poison.encode! 然后再 assert:

payload = "{\"card\": ...}"
assert_receive %Phoenix.Socket.Broadcast{topic: ^t1, event: "card:created", payload: raw_payload}
assert Poison.encode!(raw_payload) == payload