Requests
GraphQL
Build GraphQL requests from a query and variables.
GraphQL requests are JSON bodies with a query, optional variables and an optional operationName. apitest builds the body and sets Content-Type: application/json.
GraphQLQuery
GraphQLQuery takes the query and an optional map of variables:
apitest.Handler(handler).
Post("/graphql").
GraphQLQuery(
`query User($id: ID!) { user(id: $id) { name } }`,
map[string]any{"id": "1234"},
).
Expect(t).
Status(http.StatusOK).
Body(`{"data": {"user": {"name": "jon"}}}`).
End()GraphQLRequest
GraphQLRequest takes the full apitest.GraphQLRequestBody, which is needed to set the operation name:
apitest.Handler(handler).
Post("/graphql").
GraphQLRequest(apitest.GraphQLRequestBody{
Query: `query User($id: ID!) { user(id: $id) { name } }`,
Variables: map[string]any{"id": "1234"},
OperationName: "User",
}).
Expect(t).
Status(http.StatusOK).
Body(`{"data": {"user": {"name": "jon"}}}`).
End()type GraphQLRequestBody struct {
Query string `json:"query"`
Variables map[string]any `json:"variables,omitempty"`
OperationName string `json:"operationName,omitempty"`
}Asserting on GraphQL responses
GraphQL servers usually respond 200 OK even when the query fails, and report problems in an errors array. Assert on the body, or on parts of it with JSONPath, for example jsonpath.NotPresent("$.errors").
The apitest repository has a complete gqlgen example.