{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/testing-with-elixir-and-phoenix-channels","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Testing with Elixir and Phoenix: Channels\",\n  \"order\": 39,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\", \"elixir\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Testing with Elixir and Phoenix: Channels\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"RoomChannel tests\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Channel helpers tests\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"AdminChannel tests\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"UserSocket tests\")), mdx(\"p\", null, \"Channel tests, like Controller tests, simulate the broadcasting and pushing of events to the client without making an actual socket connection. By simulating the connection, your tests will run much faster and with less configuration so you can focus on testing the logic in your Channel handlers.\"), mdx(\"p\", null, \"We're going to start with our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"RoomChannel\"), \".\"), mdx(\"h2\", null, \"RoomChannel tests\"), mdx(\"p\", null, \"Just like with our controller tests, we get a lot out of the box with Phoenix. For Channels it's called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ChannelCase\"), \" rather than \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ConnCase\"), \". It's worth taking a quick look at \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"test/support/channel_case.ex\"), \" to get a sense of what you get for free with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ChannelCase\"), \".\"), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"setup\"), \" block allows us to setup each test case with a socket that's subscribed to something that we want to test, which in this case is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:lobby\"), \". We're also going assign a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" to a number and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" to nil to test for anonymous users who are not admins.\"), mdx(\"p\", null, \"To connect to the channel, we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"subscribe_and_join/2\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.ChannelTest.html#subscribe_and_join/4\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \".\"), mdx(\"p\", null, \"While you're at it, go ahead and delete the existing tests.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.RoomChannelTest do\\n  use PhoenixChat.ChannelCase\\n\\n  alias PhoenixChat.{RoomChannel, Message}\\n\\n  setup do\\n    {:ok, %{messages: []}, socket} =\\n      socket(\\\"user_id\\\", %{uuid: \\\"1144\\\", user_id: nil})\\n      |> subscribe_and_join(RoomChannel, \\\"room:lobby\\\")\\n    {:ok, socket: socket}\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Now that we have our channel set up for each of our tests, we can start interacting with it. In our first test, we're going to join a room, add messages to the database, then check to make sure the messages are returned as the payload.\"), mdx(\"p\", null, \"The first few lines add three messages to the database: two in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:1\"), \" and one in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:2\"), \". The next line calls the socket with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"%{some: :assign}\"), \" which is there to communicate that it expects a map for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"socket.assigns\"), \", then subscribes to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:1\"), \" channel. We're using pattern matching in the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{:ok, %{messages: messages}, _}\"), \" expression to match the result of our connection (which will be a list of the latest 10 messages) to the term \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"messages\"), \".\"), mdx(\"p\", null, \"We then assert that we received two messages, since two of the messages we added were added to the room we connected to: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:1\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"joining a room returns messages from the DB as payload\\\" do\\n  timestamp = Ecto.DateTime.utc()\\n  Repo.insert!(%Message{body: \\\"Foo\\\", timestamp: timestamp, room: \\\"1\\\"})\\n  Repo.insert!(%Message{body: \\\"Bar\\\", timestamp: timestamp, room: \\\"1\\\"})\\n  Repo.insert!(%Message{body: \\\"Bar\\\", timestamp: timestamp, room: \\\"2\\\"})\\n\\n  {:ok, %{messages: messages}, _} =\\n    socket(\\\"user_id\\\", %{some: :assign})\\n    |> subscribe_and_join(RoomChannel, \\\"room:1\\\")\\n\\n  assert length(messages) == 2\\nend\\n\")), mdx(\"p\", null, \"The last thing we need to test for our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"RoomChannel\"), \" is that we can push messages using our socket. To do this we're creating a valid \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"payload\"), \", then using the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"push\"), \" function  \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.ChannelTest.html#push/3\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \" to send a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message\"), \" event to the socket subscribed to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:lobby\"), \" with the payload we just defined. Recall that whenever a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message\"), \" event is sent to our room channel, it triggers the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"def handle_in(\\\"message\\\", payload, socket) do\"), \" function defined in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/channels/room_channel.ex\"), \".\"), mdx(\"p\", null, \"Then we use another assertion type called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"assert_reply\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.ChannelTest.html#assert_reply/4\",\n    \"parentName\": \"p\"\n  }, \"(docs)\"), \", which, as you might have guessed, asserts that we received a reply that contains a reference to the event that was pushed, an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":ok\"), \" atom, and the payload.\"), mdx(\"p\", null, \"Then for good measure we're going to check our database to make sure that the message we sent was in fact added to the database.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"message replies with status ok and saves message to DB\\\", %{socket: socket} do\\n  payload = %{\\n    body: \\\"hello\\\",\\n    timestamp: 1470637865914,\\n    room: \\\"lobby\\\",\\n    from: \\\"1144\\\"\\n  }\\n\\n  ref = push socket, \\\"message\\\", payload\\n  assert_reply ref, :ok, payload\\n  assert Repo.get_by(Message, payload)\\nend\\n\")), mdx(\"h2\", null, \"ChannelHelpers tests\"), mdx(\"p\", null, \"We created a few helpers to make authorization easier, so we need to test them too.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch test/channels/channel_helpers_test.exs\\n\")), mdx(\"p\", null, \"Since this is normal Elixir, we are going to import \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ExUnit.Case\"), \", which is what you would import for any other Elixir module you want to test. The functions in our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ChannelHelpers\"), \" are pure functions so they're really easy to test. This is because pure functions have no side effects and always return the same output given the same inputs.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.ChannelHelpersTest do\\n  use ExUnit.Case\\n\\n  import PhoenixChat.ChannelHelpers\\n\\nend\\n\")), mdx(\"p\", null, \"To test our authorization function, need to test both a passing and a failing test. Recall that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorize/2\"), \" takes in a payload and a function. The payload is used to determine if the user is authorized and the function is what we run if the user is authorized. In this case, the payload is \\\"test\\\" since we currently set \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorized?/1\"), \" to return true no matter what it receives, and we are passing a function that returns \\\"foo\\\". If we get that value, then the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorize/2\"), \" method worked properly.\"), mdx(\"p\", null, \"Next we test a failed authorization. We do this by passing in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"custom_authorize\"), \" function that returns false. Then we check to make sure that we received the error we expected: \\\"unauthorized\\\".\"), mdx(\"p\", null, \"The last test is just a placeholder at this point since we will always return true no matter what value we send to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorized?/1\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"authorize/2 and authorize/3\\\" do\\n  assert authorize(\\\"test\\\", fn -> \\\"foo\\\" end) == \\\"foo\\\"\\n\\n  failed_authorization = authorize(\\\"test\\\", fn -> \\\"foo\\\" end, fn _ -> false end)\\n  assert {:error, %{reason: \\\"unauthorized\\\"}} == failed_authorization\\nend\\n\\ntest \\\"authorized?/1\\\" do\\n  assert authorized?(false) == true\\nend\\n\")), mdx(\"h2\", null, \"AdminChannel tests\"), mdx(\"p\", null, \"Now we're going to write tests for our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"AdminChannel\"), \", which is going to be very similar to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"RoomChannel\"), \" tests.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch test/channels/admin_channel_test.exs\\n\")), mdx(\"p\", null, \"First we add \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"ChannelCase\"), \" since we're testing a channel, then we add our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"setup\"), \" block. We're going to use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"on_exit\"), \", which runs after every test, to call \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"delete_all_objects/1\"), \" in our list from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":ets\"), \" so we start every test with a fresh ETS table.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.AdminChannelTest do\\n  use PhoenixChat.ChannelCase\\n\\n  alias PhoenixChat.{AdminChannel, LobbyList}\\n\\n  setup do\\n    on_exit fn ->\\n      :ets.delete_all_objects(LobbyList)\\n    end\\n  end\\n\\nend\\n\")), mdx(\"p\", null, \"Our first test makes sure we can join the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"admin:active_users\"), \" channel as an admin. This is the channel from which we gain access to the list of all currently active users and populate the sidebar on our frontend.\"), mdx(\"p\", null, \"First we add some fake data to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"LobbyList\"), \", then we simulate joining the socket with a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" of \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"1\"), \", since in our application we assume that any user with a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" is an admin (anonymous users have a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \"). This is mostly the same as our other channel test.\"), mdx(\"p\", null, \"In our first assertion, we're testing that the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lobby_list\"), \" that we get back from our socket contains two items by checking its \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"length\"), \".\"), mdx(\"p\", null, \"Then we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"assert_push\"), \" to assert that we can push a new event to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lobby_list\"), \". In this case, we're adding a new anonymous user.\"), mdx(\"p\", null, \"Next we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"assert_push\"), \" our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"presence_state\"), \", which starts out with an empty payload since no presences have been tracked at this point (we're adding it now).\"), mdx(\"p\", null, \"Finally, we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"assert_push\"), \" that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"presence_diff\"), \" is pushed to the client with a payload that signifies that a presence has been tracked.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"joining admin:active_users as admin\\\" do\\n  LobbyList.insert(\\\"foo\\\")\\n  LobbyList.insert(\\\"bar\\\")\\n\\n  {:ok, %{lobby_list: lobby_list}, _socket} =\\n    socket(\\\"user_id\\\", %{user_id: 1})\\n    |> subscribe_and_join(AdminChannel, \\\"admin:active_users\\\")\\n\\n  assert length(lobby_list) == 2\\n  assert_push \\\"lobby_list\\\", %{uuid: 1}\\n  assert_push \\\"presence_state\\\", %{}\\n  assert_push \\\"presence_diff\\\", %{joins: %{\\\"1\\\" => %{}}}\\nend\\n\")), mdx(\"p\", null, \"The last thing we want to test is to make sure that non-admins aren't receiving the list of all active users.\"), mdx(\"p\", null, \"We start by connecting to the socket as an anonymous user by setting \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nil\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" to something valid.\"), mdx(\"p\", null, \"Then we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"refute_push\"), \" to refute that the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lobby_list\"), \" event is triggered with a payload. This is our way of testing \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_out/3\"), \" for \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"lobby_list\"), \", which filters non-admins from receiving the event.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"test \\\"non-admin users do not receive the 'lobby_list' event on join\\\" do\\n  {:ok, %{lobby_list: _}, _} =\\n    socket(\\\"user_id\\\", %{user_id: nil, uuid: 5})\\n    |> subscribe_and_join(AdminChannel, \\\"admin:active_users\\\")\\n\\n  refute_push \\\"lobby_list\\\", %{}\\nend\\n\")), mdx(\"h2\", null, \"UserSocket tests\"), mdx(\"p\", null, \"The last thing we need to test for our channels is our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserSocket\"), \". All we need to do to test this is insert a user into our database and make sure that the user is being assigned to our socket.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch test/channels/user_socket.exs\\n\")), mdx(\"p\", null, \"The first line adds an admin, then we connect to our UserSocket and pass the newly created admin's \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" along to it. Then we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"subscribe_and_join/3\"), \" the socket and then assert that we find each of the parameters we expect.\"), mdx(\"p\", null, \"In the second test, we do basically the same thing but as an anonymous user. If the user is anonymous, she won't have a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \", so we \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"refute\"), \" that there is one, and then assert that the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" is the same as the one we passed in.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserSocketTest do\\n  use PhoenixChat.ChannelCase\\n\\n  alias PhoenixChat.{Repo, User, UserSocket}\\n\\n  test \\\"connecting to user socket as logged-in user\\\" do\\n    admin = Repo.insert!(%User{email: \\\"admin@bar.com\\\", username: \\\"admin\\\"})\\n\\n    {:ok, socket} = connect(UserSocket, %{\\\"id\\\" => admin.id})\\n    {:ok, _, socket} = subscribe_and_join(socket, \\\"room:1\\\", %{})\\n\\n    assert socket.assigns.user_id == admin.id\\n    assert socket.assigns.email == admin.email\\n    assert socket.assigns.username == admin.username\\n  end\\n\\n  test \\\"connecting to user socket as anonymous user\\\" do\\n    {:ok, socket} = connect(UserSocket, %{\\\"uuid\\\" => 25})\\n    {:ok, _, socket} = subscribe_and_join(socket, \\\"room:25\\\", %{})\\n\\n    refute socket.assigns.user_id\\n    assert socket.assigns.uuid == 25\\n  end\\nend\\n\")));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Testing with Elixir and Phoenix: Channels RoomChannel tests Channel helpers tests AdminChannel tests UserSocket tests Channel tests, like…","frontmatter":{"title":"Testing with Elixir and Phoenix: Channels","order":39,"active":true,"free":false,"tech":["phoenix","elixir"]}}},"pageContext":{"slug":"testing-with-elixir-and-phoenix-channels","prevNode":{"frontmatter":{"title":"Testing with Elixir and Phoenix: Controllers","active":true,"free":false,"order":38,"tech":["phoenix","elixir"]},"fields":{"slug":"testing-with-elixir-and-phoenix-controllers"}},"nextNode":{"frontmatter":{"title":"Testing with Elixir and Phoenix: Models","active":true,"free":false,"order":40,"tech":["phoenix","elixir"]},"fields":{"slug":"testing-with-elixir-and-phoenix-models"}}}},"staticQueryHashes":["1723017916"]}