Search⌘ K
AI Features

Setup Block for Testing JSON-based APIs

Explore how to create a setup block for testing JSON-based APIs in Phoenix with ExUnit. Learn to configure ConnCase for HTTP testing, handle JWT headers, and manage the test sandbox environment to build effective API tests.

Testing the update endpoint

In the included repo, NotSkull, let’s create a new test file at test/not_skull_web/controllers/json_api/user_controller_test.exs.

Note: We’ve added nesting under json_api to avoid conflicting with the tests for the user controller that we used for the server-rendered HTML endpoint.

The following code will add a basic structure and setup block to the file we created:

Elixir
#file path -> test/not_skull_web/controllers/json_api/user_controller_test.exs
defmodule NotSkullWeb.JsonApi.UserControllerTest do
use NotSkullWeb.ConnCase, async: false
alias NotSkull.Accounts.User
describe "PUT /api/users/:id" do
setup context do
{:ok, user} = Factory.insert(:user)
conn_with_token =
put_req_header(
context.conn,
"authorization",
"Bearer " <> sign_jwt(user.id)
)
Map.merge(context, %{user: user, conn_with_token: conn_with_token})
end
end
end

A couple of things to note here:

  • When starting a new Phoenix project, the generators will create a few different ExUnit test cases. One of them, ConnCase, or specifically NotSkull.ConnCase in our app, will be used as the test case for all the HTTP-based interfaces. As seen on line 3, ...