Search⌘ K

Error Test for JSON-based APIs

Explore how to create error tests for JSON APIs in Phoenix with ExUnit. Understand how to verify HTTP status codes, check response data structure, and ensure no unwanted database changes occur after invalid inputs.

We'll cover the following...

It’s common to have the success tests before the error tests, but that doesn’t mean we have to write them in that order.

Defining an error test

We’re going to start with the simplest test for this endpoint: our error case. Let’s add the following test inside of the describe block in user_controller_test.exs:

Elixir
#file path -> test/not_skull_web/controllers/user_controller_test.exs
#add this code at the indicated place mentioned in comments of test/not_skull_web/controllers/
#user_controller_test.exs in the playground widget
test "error: does not update, returns errors when given invalid attributes",
%{
conn_with_token: conn_with_token,
user: existing_user
} do
conn =
put(conn_with_token, "/api/users/#{existing_user.id}", %{name: ""})
assert body = json_response(conn, 422)
user_from_db = Repo.get(User, existing_user.id)
assert user_from_db == existing_user
actual_errors = body["errors"]
refute Enum.empty?(actual_errors)
expected_error_keys = ["field", "message"]
for error <- actual_errors do
assert_unordered_lists_are_equal(
actual: Map.keys(error),
expected: expected_error_keys
)
end
end

Let’s go over some more important features of this test:

  • The test accepts a context from the setup block, in this case giving it a user and a Plug.Conn that contains a header ...