coen.bakker

coen.bakker

TLDR; In Wallaby, how do I correctly use execute_script() before an assertion? Does execute_script(_, _, _, assertion_callback) ensure synchronous code execution? But execute_script/2 does not?

I am trying to test an infinity scrolling implementation that uses LiveView’s streams with Wallaby.

My original test looked like this.

  @chat_window Query.data("role", "chat-window")
  @n_posts 40
  test "user scrolls up to see past posts", %{session: session} do
    posts = many_posts(@n_posts)
    topic = insert!(:topic, name: "General", posts: posts)
    groups = [insert!(:welcome_group, topics: [topic])]
    user = insert!(:user, groups: groups)

    session
    |> log_in_user(user)
    |> visit(~p"/groups")
    |> find(@chat_window)

    |> assert_in_viewport("[data-role=\"post\"]:first-child")

    |> scroll_chat_up_a_bit()
    |> refute_in_viewport("[data-role=\"post\"]:first-child")

    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> scroll_chat_up_a_bit()
    |> assert_in_viewport("[data-role=\"post\"]:nth-child(#{@n_posts})")
  end

  defp assert_in_viewport(parent, selector) do
    execute_script(parent,
      """
      const post = document.querySelector(arguments[0]);

      if (!post) return false;

      const isInViewport = (element) => {
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        )
      }

      return isInViewport(post);
      """,
      [selector],
      fn resp -> assert resp == true end
    )
  end

  defp refute_in_viewport(parent, selector) do
    execute_script(parent,
      """
        const post = document.querySelector(arguments[0]);

        const isInViewport = (element) => {
          const rect = element.getBoundingClientRect();
          return (
              rect.top >= 0 &&
              rect.left >= 0 &&
              rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
              rect.right <= (window.innerWidth || document.documentElement.clientWidth)
          )
        }

        return isInViewport(post);
      """,
      [selector],
      fn resp -> assert resp == false end
    )
  end

  defp scroll_chat_up_a_bit(parent) do
    execute_script(parent,
      """
      const chat = document.querySelector('[data-role="chat-window"');
      chat.scrollBy(0, -400);
      """
    )
  end

  defp many_posts(amount) do
    Enum.reduce(1..amount, [], fn n, acc ->
      [insert!(:post, content: "Post #{n}") | acc ]
    end)
  end

This results in unreliable test results. Most of the time the test fails. Sometimes it doesn’t. If I add some :timer.sleep/1 time, the test passes consistently.

I reckoned the problem with my original test was code execution order. I adjusted my test to make use of the optional callback argument of the execute_script\4 function. This is the new test.

  @chat_window Query.data("role", "chat-window")
  @n_posts
  test "user scrolls up to see past posts", %{session: session} do
    posts = many_posts(@n_posts)
    topic = insert!(:topic, name: "General", posts: posts)
    groups = [insert!(:welcome_group, topics: [topic])]
    user = insert!(:user, groups: groups)

    session
    |> log_in_user(user)
    |> visit(~p"/groups")
    |> find(@chat_window)
    |> assert_in_viewport("[data-role=\"post\"]:first-child")

    session
    |> scroll_chat_up_a_bit(1, fn s ->
     refute_in_viewport(s, "[data-role=\"post\"]:first-child")
    end)

    session
    |> scroll_chat_up_a_bit(12, fn s ->
      assert_in_viewport(s, "[data-role=\"post\"]:nth-child(#{@n_posts})")
    end)
  end

  defp assert_in_viewport(parent, selector) do
    execute_script(parent,
      """
      const post = document.querySelector(arguments[0]);

      if (!post) return false;

      const isInViewport = (element) => {
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        )
      }

      return isInViewport(post);
      """,
      [selector],
      fn resp -> assert resp == true end
    )
  end

  defp refute_in_viewport(parent, selector) do
    execute_script(parent,
      """
        const post = document.querySelector(arguments[0]);

        if (!post) throw new Error("Bottom post not found");

        const isInViewport = (element) => {
          const rect = element.getBoundingClientRect();
          return (
              rect.top >= 0 &&
              rect.left >= 0 &&
              rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
              rect.right <= (window.innerWidth || document.documentElement.clientWidth)
          )
        }

        return isInViewport(post);
      """,
      [selector],
      fn resp -> assert resp == false end
    )
  end

  defp scroll_chat_up_a_bit(parent, 0, callback), do: callback.(parent)

  defp scroll_chat_up_a_bit(parent, n, callback) when n > 0 do
    execute_script(parent,
      """
      const chat = document.querySelector('[data-role="chat-window"');
      chat.scrollBy(0, -400);
      """,
      [],
      fn _ -> scroll_chat_up_a_bit(parent, n - 1, callback) end
    )
  end

I was surprised to find that the second test also returns inconsistent test results.

My priority is to understand what is going wrong here. Any ideas?

Secondarily, it could very well be that I am over complicating this test. Better approaches are more than welcome. :slight_smile:

P.S. There is a small section about asynchronous JavaScript in hexdocs of Wallaby, but following its advice did not solve my problem.

First 3 of 3 Posts Switch mode

coen.bakker

coen.bakker OP

It seems maybe fluctuations in room temperature are causing the issue :sweat_smile:.

sodapopcan

sodapopcan

I don’t have a great answer but since you are getting any traction I thought I’d chime in.

Resorting to sleeps in e2e testing is just a fact of life, unfortunately. Even if you don’t call it yourself, most e2e testing frameworks, including Wallaby, are doing it for you. Anything that asserts an element is on the page will keep re-trying to find it for a fixed number of seconds. See the retry definition here which includes a :timer.sleep. That function is an underpinning of the has_text?, has_value?, execute_query, and find functions.

coen.bakker

coen.bakker OP

Oh yes. That’s great to know and makes sense.

Thank you.

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New

We're in Beta

About us Mission Statement