Writing Controller Test Case in Phoenix

I am very new to elixir. Kindly help me to write a test case for the controller.
Your help would be really appreciated.
Thank you.

defmodule CheckReactWeb.UserController do
  use CheckReactWeb, :controller

  def get_conns(conn, _params) do
    users = [
      %{name: "Joe", email: "joe@example.com", password: "topsecret", stooge: "moe"},
      %{name: "Anne", email: "anne@example.com", password: "guessme", stooge: "larry"},
      %{name: "Franklin", email: "franklin@example.com", password: "guessme", stooge: "curly"}
    ]

    json(conn, users)
  end
end

defmodule CheckReactWeb.Router do
  use CheckReactWeb, :router

  pipeline :api do
    plug(:accepts, ["json"])
  end

  scope "/api", CheckReactWeb do
    pipe_through(:api)

    get("/users", UserController, :get_conns)
  end
end

What have you written so far? Have you read the Phoenix docs on testing controllers? Are you stuck on a particular error?

1 Like

I am not getting any response body.

defmodule CheckReactWeb.UserController do
  use CheckReactWeb.ConnCase
  alias CheckReactWeb.UserController

  test "GET /", %{conn: conn} do
    resp = UserController.get_conns(conn, {}) |> json_response(200)
    IO.puts("#{inspect(resp)}")
  end

To test the route /api/users which calls UserController.get_conns/2 you could use Phoenix.ConnTest.

test "get /api/users returns json response" do
  conn = get(build_conn(), "/api/users")
  assert json_response(conn, 200)
end

I tried doing this, but I got this error.

Your test module name is wrong, it should be CheckReactWeb.UserControllerTest, not CheckReactWeb.UserController.

Here’s how you would test your UserController:

test "GET /users", %{conn: conn} do
  conn = get(conn, Routes.user_path(conn, :get_conns))
  assert json_response(conn, 200) == [whatever data you want to put here.]
2 Likes

Hi Daksh, please don’t use images to show text/code. Many of our users browse the forum on their mobiles or on internet with limited bandwidth and images slow things down for them.

Thanks for your understanding :slight_smile:

2 Likes