如何在通道测试中自动将eTecto struct序列化与JSON响应?正如我在文档The event’s message must be a serializable map
中看到的那样,我在答案和教程中发现,当我在模型中使用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}
然后,它上升不匹配错误,而在有效载荷中未序列化结构(我试图匹配派生的模型filelds):
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