Phoenix 的好处之一,是不同治理层有各自清楚的测试入口。
#1. Controller / HTTP:ConnTest
test "GET /dispatches", %{conn: conn} do
conn = get(conn, ~p"/dispatches")
assert html_response(conn, 200) =~ "今日调度公报"
end#2. LiveView:Phoenix.LiveViewTest
test "can create dispatch", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/live/dispatches")
html =
view
|> form("form", dispatch: %{title: "东门警报"})
|> render_submit()
assert html =~ "东门警报"
end#3. Channel:Phoenix.ChannelTest
test "report_incident broadcasts to district" do
{:ok, _, socket} =
socket(CityWeb.UserSocket, "user:1", %{current_user: %{id: 1}})
|> subscribe_and_join(CityWeb.DistrictChannel, "district:42")
ref = push(socket, "report_incident", %{"title" => "南门拥堵"})
assert_reply ref, :ok, %{id: _id}
assert_broadcast "incident_reported", %{title: "南门拥堵"}
end这种分层测试体验非常 Phoenix:
窗口怎么回:测 HTTP
中控室怎么反应:测 LiveView
频道塔怎么广播:测 Channel不是所有东西都塞进 E2E 黑箱里。