inertia_phoenix icon indicating copy to clipboard operation
inertia_phoenix copied to clipboard

Controller Testing Documentation

Open garlandcrow opened this issue 4 years ago • 1 comments

I've starting using this in a new project I am working on and during controller testing I made a helper that I add to my conn_case.ex that maybe other people would find useful? I can add some documentation as a PR if this is something anyone would want. If not, just putting this here in case it helps someone.

def inertia_response(conn, status \\ 200) do
    response = Phoenix.ConnTest.html_response(conn, status)

    case Regex.run(~r/data-page=\"(.+?)\"/, response) do
      [_, injected_data] ->
        injected_data |> String.replace(""", "\"") |> Jason.decode!()

      _ ->
        nil
    end
  end

Then you can use it a test like:

conn = get(conn, Routes.customer_quotations_path(conn, :index))
response = inertia_response(conn, 200)

Which gives you a map of the inertia injected data on the page:

%{
  "component" => "QuotationList",
  "props" => %{
    "quotations" => [
      %{
        "completed" => false,
        "id" => 1,
        "status" => "awaiting_quotation",
        "updated_at" => "2020-09-04T02:02:14"
      }
    ]
  },
  "url" => "/quotations",
  "version" => "1"
}

This can be useful to assert the correct component is being rendered, or assert about the props being injected into the component.

garlandcrow avatar Sep 04 '20 02:09 garlandcrow

@garlandcrow This is great. Would you mind doing a PR with some docs?

tmartin8080 avatar Sep 29 '20 12:09 tmartin8080