amaterasu

amaterasu

Testing LiveComponent with JS Hook

I need to test that I can create a post having one category (chosen from an async loaded list) on my admin site.

I have a LiveComponent for a select which uses Tom Select JS with a phx-hook like this:

    ~H"""
    <.field_wrapper errors={@errors} name={@name} class={@wrapper_class}>
      <div
        id={"#{@id}"}
        phx-hook="ComboBox"
      >
        <div id={"#{@id}_wrapper"} phx-update="ignore">
          <.field_label required={@required} for={@id} class={@label_class}>
            <%= @label %>
          </.field_label>
          <div class="combo-box-wrapper">
            <select
              class={["combo-box", @class]}
              multiple={@multiple}
              name={@name}
              required={@required}
              {@rest}
            >
              <option :for={{value, label} <- @value} selected value={value}><%= label %></option>
            </select>
          </div>
        </div>
      </div>
    </.field_wrapper>

Here’s the JS Hook:

Hooks.ComboBox = {
  mounted() {
    this.init(this.el)
  },
  init: async function (el) {
    const settings = {
      preload: 'focus',
      load: (query, callback) => {
        const params = {query: query}
        this.pushEventTo(el, 'fetch_association', params, (data) => callback(data.results))
       }
     }

    new TomSelect(el.querySelector('select.combo-box'), settings)
  },
}

The <option>s for the <select> are loaded when the input is focused.
Before focusing, the select only has the options which are already associated to the post (which are empty in tests).

My test:

  @create_attrs %{
    category_id: "123",
    title: "some title"
  }

  ...

    test "saves new post", %{conn: conn} do
      {:ok, view, _html} = live(conn, ~p"/posts/new")

      assert view
             |> form("#post-form", post: @create_attrs)
             |> render_submit()

      assert_patch(view, ~p"/posts")
    end

I’m getting this error:

value for select "post[category_id]" must be one of [], got: "123"

I’m guessing that this is because the <option> list is empty and Phoenix checks for a list of possible values?

How can I test this since the <option>s are filled by the JS hook? I see that render_hook exists, but of course it doesn’t run the JS part.
I guess I can also avoid testing the JS hook itself by injecting a list of <option>s for this test’s purpose, but I’m not sure how.

Thank you!

Most Liked

trisolaran

trisolaran

That’s right. form/3 mimics what the user is supposed to be able to do on the form, so you can’t select an option that doesn’t exist yet.

However, you can easily sidestep this limitation by passing some values in render_submit/2 directly.

arcanemachine

arcanemachine

I believe you would need to use something like Playwright to test the JS. But your code shouldn’t be getting that error IMO. The Elixir side of the code should be picking up your category_id since it doesn’t really care about the JS implementation.

It looks like the error is suggesting that the category_id field expects a list [], which is strange. Did you create the category_id field as an :array in your migration? I believe that a foreign key should be represented like this in your migration:

add :category_id, references(:categories, on_delete: :delete_all), null: false

If you don’t have this, you could create a new migration, or just edit the existing migration and run mix ecto.reset (which will completely reset the database for the project, be ye warned).

sodapopcan

sodapopcan

Ah sorry, your initial error confused me as I read it as you were getting a type-mismatch. I did some tests but not with an empty <select> because I thought it was getting some default values, even though you clearly said it was the JS that populates it. D’oh.

I knew you could pass form data to it but never knew that’s why. TIL!

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New

Other popular topics Top

grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54092 488
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New