Prevents "DBConnection.ConnectionError: client exited" errors in Phoenix LiveView tests
Add to your mix.exs:
def deps do
[
{:wait_for_async_assigns, "~> 0.1.0", only: :test}
]
endImport in your test case module (e.g., test/support/conn_case.ex):
defmodule MyAppWeb.ConnCase do
use ExUnit.CaseTemplate
using do
quote do
import Phoenix.ConnTest
import Phoenix.LiveViewTest
import WaitForAsyncAssigns
@endpoint MyAppWeb.Endpoint
end
end
endImport the formatter config in .formatter.exs:
[
import_deps: [:phoenix, :wait_for_async_assigns],
# ...
]Call wait_for_async_assigns/1 at the end of LiveView tests that use async operations:
test "loads data asynchronously", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/products")
html = render_async(view)
assert html =~ "Products"
wait_for_async_assigns(view)
endThe function waits for all async tasks to complete before the test exits, preventing connection errors.
Custom timeout:
wait_for_async_assigns(view, 10_000) # Wait up to 10 secondsDefault timeout is 100ms (configurable via config :ex_unit, assert_receive_timeout: 1000).
This package includes a Credo check that warns when LiveView tests are missing wait_for_async_assigns/1.
Add to .credo.exs:
%{
configs: [
%{
name: "default",
requires: ["deps/wait_for_async_assigns/lib/credo/check/wait_for_async_assigns.ex"],
checks: %{
enabled: [
{Credo.Check.WaitForAsyncAssigns, []}
]
}
}
]
}MIT License - see LICENSE for details.
Contributions are welcome! Please open an issue or pull request on GitHub.
Created by Mario Uher.
