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" => [
//key-value pair
]
}
}
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:
@query """
{
courses {
name
}
}
"""
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"}]}}%
Have you already checked whether your test database contains the same data as your dev database? The default way in Phoenix is to use different environments for test/dev/prod and therefore you should find the respective .exs
file within the config folder of your project and this is also where your database connection for the test/dev/prod environment is defined.
When you start Phoenix with iex -S mix phx.server
your environment should be dev per default (if your MIX_ENV
is empty).
Just for the sake of completeness: You can execute MIX_ENV=test iex -S mix phx.server
then you would use the test environment and you can therefore check with your CURL command if your query returns a result for the test
environment/database.