Testing Our Query

GraphiQL is a great tool to explore our API and when we’d like to manually run a query, but it’s not a replacement for a test suite. We’ll use ExUnit to add tests for our Absinthe schema to make sure our queries work now and later on to prevent regressions. Our future selves will appreciate the forethought.

ExUnit is bundled with Elixir, so no dependencies are required. Since our PlateSlate application is using Phoenix, ExUnit has already been set up with a preconfigured test harness that we can use.

Because we know our users are going to use the API by hitting /api, we can treat our API just as we would a Phoenix controller, using the PlateSlate.ConnCase helper module that Phoenix generously generated for us:

1: defmodule​ PlateSlateWeb.Schema.Query.MenuItemsTest ​do
use​ PlateSlateWeb.ConnCase, ​async:​ true
setup ​do
5:  PlateSlate.Seeds.run()
end
@query ​"""
{
10:  menuItems {
name
}
}
"""
15:  test ​"​​menuItems field returns menu items"​ ​do
conn = build_conn()
conn = get conn, ​"​​/api"​, ​query:​ @query
assert json_response(conn, 200) == %{
"​​data"​ => %{
20: "​​menuItems"​ => [
%{​"​​name"​ => ​"​​Reuben"​},
%{​"​​name"​ => ​"​​Croque Monsieur"​},
%{​"​​name"​ => ​"​​Muffuletta"​},
# Rest of items
25:  ]
}
}
end
30: end

The setup block loads our seed data as a convenience. The test itself starts by building a connection. Then it passes the @query module attribute we defined previously (making use of Elixir’s handy multiline """ string literal) as the :query option, which is what Absinthe.Plug expects. The response is then checked to make sure that it has an HTTP 200 status code and includes the JSON data that we expect to see.

Running the test gives us exactly what we were hoping for:

 $ ​​mix​​ ​​test​​ ​​test/plate_slate_web/schema/query/menu_items_test.exs
 .
 
 Finished in 0.2 seconds
 1 test, 0 failures

After a little compilation, a passing test!

We’ll continue to build tests out this way as our API grows. These tests exercise a lot of our system, from HTTP requests through JSON serialization, helping to reduce our stress by keeping us confident that changes elsewhere in the application aren’t affecting our GraphQL users.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.189.199