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.
We're going to start with our RoomChannel.
Just like with our controller tests, we get a lot out of the box with Phoenix. For Channels it's called ChannelCase rather than ConnCase. It's worth taking a quick look at test/support/channel_case.ex to get a sense of what you get for free with ChannelCase.
The 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 room:lobby. We're also going assign a uuid to a number and user_id to nil to test for anonymous users who are not admins.
To connect to the channel, we use subscribe_and_join/2 (docs).
While you're at it, go ahead and delete the existing tests.
defmodule PhoenixChat.RoomChannelTest do use PhoenixChat.ChannelCase alias PhoenixChat.{RoomChannel, Message} setup do {:ok, %{messages: []}, socket} = socket("user_id", %{uuid: "1144", user_id: nil}) |> subscribe_and_join(RoomChannel, "room:lobby") {:ok, socket: socket} end ...endNow 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.
The first few lines add three messages to the database: two in room:1 and one in room:2. The next line calls the socket with user_id and %{some: :assign} which is there to communicate that it expects a map for socket.assigns, then subscribes to the room:1 channel. We're using pattern matching in the {:ok, %{messages: messages}, _} expression to match the result of our connection (which will be a list of the latest 10 messages) to the term messages.
We then assert that we received two messages, since two of the messages we added were added to the room we connected to: room:1.
test "joining a room returns messages from the DB as payload" do timestamp = Ecto.DateTime.utc() Repo.insert!(%Message{body: "Foo", timestamp: timestamp, room: "1"}) Repo.insert!(%Message{body: "Bar", timestamp: timestamp, room: "1"}) Repo.insert!(%Message{body: "Bar", timestamp: timestamp, room: "2"}) {:ok, %{messages: messages}, _} = socket("user_id", %{some: :assign}) |> subscribe_and_join(RoomChannel, "room:1") assert length(messages) == 2endThe last thing we need to test for our RoomChannel is that we can push messages using our socket. To do this we're creating a valid payload, then using the push function (docs) to send a message event to the socket subscribed to room:lobby with the payload we just defined. Recall that whenever a message event is sent to our room channel, it triggers the def handle_in("message", payload, socket) do function defined in web/channels/room_channel.ex.
Then we use another assertion type called assert_reply (docs), which, as you might have guessed, asserts that we received a reply that contains a reference to the event that was pushed, an :ok atom, and the payload.
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.
test "message replies with status ok and saves message to DB", %{socket: socket} do payload = %{ body: "hello", timestamp: 1470637865914, room: "lobby", from: "1144" } ref = push socket, "message", payload assert_reply ref, :ok, payload assert Repo.get_by(Message, payload)endWe created a few helpers to make authorization easier, so we need to test them too.
$ touch test/channels/channel_helpers_test.exsSince this is normal Elixir, we are going to import ExUnit.Case, which is what you would import for any other Elixir module you want to test. The functions in our 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.
defmodule PhoenixChat.ChannelHelpersTest do use ExUnit.Case import PhoenixChat.ChannelHelpersendTo test our authorization function, need to test both a passing and a failing test. Recall that 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 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 authorize/2 method worked properly.
Next we test a failed authorization. We do this by passing in a custom_authorize function that returns false. Then we check to make sure that we received the error we expected: "unauthorized".
The last test is just a placeholder at this point since we will always return true no matter what value we send to authorized?/1.
test "authorize/2 and authorize/3" do assert authorize("test", fn -> "foo" end) == "foo" failed_authorization = authorize("test", fn -> "foo" end, fn _ -> false end) assert {:error, %{reason: "unauthorized"}} == failed_authorizationendtest "authorized?/1" do assert authorized?(false) == trueendNow we're going to write tests for our AdminChannel, which is going to be very similar to our RoomChannel tests.
$ touch test/channels/admin_channel_test.exsFirst we add ChannelCase since we're testing a channel, then we add our setup block. We're going to use on_exit, which runs after every test, to call delete_all_objects/1 in our list from :ets so we start every test with a fresh ETS table.
defmodule PhoenixChat.AdminChannelTest do use PhoenixChat.ChannelCase alias PhoenixChat.{AdminChannel, LobbyList} setup do on_exit fn -> :ets.delete_all_objects(LobbyList) end endendOur first test makes sure we can join the 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.
First we add some fake data to our LobbyList, then we simulate joining the socket with a user_id of 1, since in our application we assume that any user with a user_id is an admin (anonymous users have a uuid). This is mostly the same as our other channel test.
In our first assertion, we're testing that the lobby_list that we get back from our socket contains two items by checking its length.
Then we use assert_push to assert that we can push a new event to lobby_list. In this case, we're adding a new anonymous user.
Next we assert_push our presence_state, which starts out with an empty payload since no presences have been tracked at this point (we're adding it now).
Finally, we assert_push that presence_diff is pushed to the client with a payload that signifies that a presence has been tracked.
test "joining admin:active_users as admin" do LobbyList.insert("foo") LobbyList.insert("bar") {:ok, %{lobby_list: lobby_list}, _socket} = socket("user_id", %{user_id: 1}) |> subscribe_and_join(AdminChannel, "admin:active_users") assert length(lobby_list) == 2 assert_push "lobby_list", %{uuid: 1} assert_push "presence_state", %{} assert_push "presence_diff", %{joins: %{"1" => %{}}}endThe last thing we want to test is to make sure that non-admins aren't receiving the list of all active users.
We start by connecting to the socket as an anonymous user by setting user_id to nil and uuid to something valid.
Then we refute_push to refute that the lobby_list event is triggered with a payload. This is our way of testing handle_out/3 for lobby_list, which filters non-admins from receiving the event.
test "non-admin users do not receive the 'lobby_list' event on join" do {:ok, %{lobby_list: _}, _} = socket("user_id", %{user_id: nil, uuid: 5}) |> subscribe_and_join(AdminChannel, "admin:active_users") refute_push "lobby_list", %{}endThe last thing we need to test for our channels is our 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.
$ touch test/channels/user_socket.exsThe first line adds an admin, then we connect to our UserSocket and pass the newly created admin's id along to it. Then we subscribe_and_join/3 the socket and then assert that we find each of the parameters we expect.
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 user_id, so we refute that there is one, and then assert that the uuid is the same as the one we passed in.
defmodule PhoenixChat.UserSocketTest do use PhoenixChat.ChannelCase alias PhoenixChat.{Repo, User, UserSocket} test "connecting to user socket as logged-in user" do admin = Repo.insert!(%User{email: "admin@bar.com", username: "admin"}) {:ok, socket} = connect(UserSocket, %{"id" => admin.id}) {:ok, _, socket} = subscribe_and_join(socket, "room:1", %{}) assert socket.assigns.user_id == admin.id assert socket.assigns.email == admin.email assert socket.assigns.username == admin.username end test "connecting to user socket as anonymous user" do {:ok, socket} = connect(UserSocket, %{"uuid" => 25}) {:ok, _, socket} = subscribe_and_join(socket, "room:25", %{}) refute socket.assigns.user_id assert socket.assigns.uuid == 25 endend