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 https://github.com/RicardoTrindade/NewHorizons-Api

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

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

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

    fish
  end

  test "query: all_fishes", %{conn: conn} do
    fish_fixture()

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

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

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.

Published 22 May 2020

Biomedical engineer, with a keen interest in machine learning currently working as a fullstack developer at Marley Spoon. Ruby, Kotlin, Typescript and Elixir
Ricardo Trindade on Twitter