Testing an initially hidden form: using `put_connect_params()`

I have a form that is a live component that shows when :form? == true and :form_action equals a valid value (:create or :edit). I want to test whether this form submits properly.

To test my form I assumed that I first need to show the form, since on initial render it is hidden. Am I correct to say I can use put_connect_params() to do just that? I assumed as much, but my test indicates that the form element is not found.

  test "create task", %{conn: conn} do
    conn = put_connect_params(conn, %{form?: true, form_action: :create})
    {:ok, view, _html} = live(conn, "/")

    assert view |> element(~s{[data-task-form]}) |> has_element?()
    # rest of test, where I submit the form with valid form values
  end

Previously, I showed the form by triggering the button responsible for showing the form, by using render_click(). This causes :form? == true and sets a valid value for :form_action. This test indicates that indeed the form has opened.

  test "create task", %{conn: conn} do
    {:ok, view, _html} = live(conn, "/")

    view = render_click(view, "open_form", %{"action" => "create"})
    assert view =~ "Task form"
  end

I need, however, to set the form field values and trigger a form submit. From what I understand I cannot do so in the test directly above, because render_click returns a rendered (and thus stringified) view.

So my question is: assuming no other mistakes in my code, is put_connect_params() indeed the right path to show the form in my test?

Ty.

So I’m not sure about put_connect_params but, you can extend your second test:

Firstly, don’t re-bind the view variable. The view variable is a test wrapper around your LV process

 test "create task", %{conn: conn} do
    {:ok, view, _html} = live(conn, "/")

    html = render_click(view, "open_form", %{"action" => "create"})
    assert html =~ "Task form"

   # Now you can use view to manipulate the form
   view
   |> form("#my-form", %{form_data: %{mykey: "myvalue"}})
   |> render_submit() # Returns rendered html you can assert on
  end
1 Like

Thank you.

I see that I didn’t quite have the right mental model of what view is in testing and the wrong idea about what the render_... functions return.

And the test indeed works now. (And passes :wink: ).

1 Like