Testing a graphql api query

Hello everyone I’m just new to Elixir, generally new to FP. So basically I try to learn Elixir and afterwards jump to building a graphql api server.

I read and follow the book “Craft GraphQL APIs in Elixir with Absinthe” and stuck at the testing of a graphql query.

Here’s what the book said:

test "menuItems field returns menu items" do
    conn = build_conn()
    conn = get conn, "/api", query: @query
    assert json_response(conn, 200) == %{
      "data" => %{
        "menuItems" => [
           //omitted
        ]
      }
   }
end

Here’s what the I attempt , I noticed that in my local machine when I make a query it uses POST method rather than GET method so I change it to post instead:

test "courses field returns courses" do
  conn = build_conn()
  conn = post conn, "api/graphiql", query: @query
  assert json_response(conn, 200) === %{
    "data" => %{
      "courses" => [
        %{"name" => "BSIT"},
        %{"name" => "BSCS"},
        %{"name" => "BSBA"}
      ]
    }
  }
end

Then when I run the test it fails because the query returns empty result.

Assertion with === failed
 code:  assert json_response(conn, 200) === %{"data" => %{"courses" => [%{"name" => "BSIT"}, %{"name" => "BSCS"}, %{"name" => "BSBA"}]}}
 left:  %{"data" => %{"courses" => []}}
 right: %{"data" => %{"courses" => [%{"name" => "BSIT"}, %{"name" => "BSCS"}, %{"name" => "BSBA"}]}}
 stacktrace:
   test/voting_system_web/query/course_test.exs:15: (test)

Then I try testing the query through curl and the query works and returns a result.

curl -X POST -H "Content-Type: application/json" --data '{ "query": "{ courses { name } }"}' http://localhost:4000/api/graphiql
{"data":{"courses":[{"name":"BSIT"},{"name":"BSCS"},{"name":"BSBA"}]}}% 

I’m sorry if this is a noob question but I want to learn so maybe anyone can help me. thank you.

Hey @Nullstrike can you show the resolver you have on the courses field? Have you inserted courses into the database for that test case?

1 Like

I’m actually noob not knowing that it is my mistake. Phoenix creates a test database which I didn’t know since I didn’t see it in the book.

So I don’t know how to seed the table with data as I encountered several errors (Ecto.Association.Preloaded) when I try to Repo.insert! on a parent table, the Student table which is a child table it also needed, thus I manually inserted data through the test database.

I’m curious if this is built-in helper or function in Phoenix

setup do
  PlateSlate.Seeds.run()
end

setup is part of ExUnit: https://hexdocs.pm/ex_unit/ExUnit.Callbacks.html#setup/1

PlateSlate.Seeds.run() is a function specifically built in the book example.