te_chris

te_chris

How to test a live_session on_mount handler that sets assigns

I’m running into an edge case with phoenix testing. I’ve got an on_mount handler behaving like a plug which creates a db session for a given client:

defmodule SgWeb.InitSessionId do
  @moduledoc """
  Adds the DB session ID to the assigns
  """
  import Phoenix.Component
  alias Sg.Sessions

  def on_mount(:default, _params, %{"client_id" => client_id}, socket) do
    session =
      case Sessions.get_session_by_client_id(client_id) do
        nil ->
          {:ok, session} = Sessions.create_session(%{client_id: client_id})
          session

        existing_session ->
          existing_session
      end

    {:cont, assign(socket, session_id: session.id)}
  end
end

However, whenever I try to test this as one would a plug, the assign function blows up and tells me I need to use render_component. I understand the logic, generally, but there has to be a way around this - I’m literally following a use case described in the docs in this instance (Phoenix.LiveView — Phoenix LiveView v0.19.5). Is there an easy way to mock a socket/assigns without triggering the exceptions?

Marked As Solved

sodapopcan

sodapopcan

Have you tried this?

socket = %Phoenix.LiveView.Socket{}

It seemed to do the trick for me.

Also Liked

sodapopcan

sodapopcan

I should be clear that I was just testing out your example and think Chris’ suggestion is the way to go.

Personally, I forgo unit testing these hooks and just test their effects in each LiveView they’re used in. I make a helper for this, kind of like how phx_gen_auth does with its generated register_and_log_in_user test helper. But obviously if you want a unit test that’s absolutely fine, I’m just sharing!

Speaking of phx_gen_auth, it actually does generate unit tests for its hooks that look like your tests! For example:

test "authenticates current_user based on a valid user_token ", %{conn: conn, user: user} do
  user_token = Accounts.generate_user_session_token(user)
  session = conn |> put_session(:user_token, user_token) |> get_session()

  {:cont, updated_socket} =
    UserAuth.on_mount(:ensure_authenticated, %{}, session, %LiveView.Socket{})

  assert updated_socket.assigns.current_user.id == user.id
end

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
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
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
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 49522 488
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement