All Articles

Testing GraphQL in Elixir

In the case you’ve read my post on Medium about the Animal Crossing New Horizons GraphQL API. In the end I said that one of the improvements was that I would add some tests to the GraphQL API. Well here they are. Just a reminder that the full code can be seen in

defmodule NewhorizonsapiWeb.SchemaTest do
  use NewhorizonsapiWeb.ConnCase
  alias Newhorizonsapi.Animals

  @user_query """
  query AllFish {
    all_fishes {
  @valid_attrs %{name: "Dace", price: 42, location: "Pond"}

  def fish_fixture(attrs \\ %{}) do
    {:ok, fish} =
      |> Enum.into(@valid_attrs)
      |> Animals.create_fish()


  test "query: all_fishes", %{conn: conn} do

    conn =
      post(conn, "/api", %{
        "query" => @user_query

    assert json_response(conn, 200) == %{"data" => %{"all_fishes" => [%{"name" => "Dace"}]}}

Here is how the test file schema_test.exs looks. Notice the fish_fixture method which is used to populate the mock database. And in the end, testing the api is just a simple request spec, you’re hitting the graphql endpoint with a query and asserting against the parsed response, pretty simple I would say.