Replies: 2 comments 8 replies
-
There are two ways to test resolvers: Unit testing resolver functionsIn this approach you mock def test_teacher_resolver_returns_teacher_if_valid_id_is_given(teacher_fixture):
info = Mock(context={})
result = resolve_teacher(None, info, id=teacher_fixture.id)
assert result == teacher_fixture Pros
Cons
Testing with test clientIn this approach you use test client to send GraphQL query to your API, then inspect JSON response. If you are using Django, you may use their test client, for ASGI apps HTTPX library also has one. def test_teacher_query_returns_teacher_if_valid_id_is_given(teacher_fixture, run_graphql_query):
query = """
query GetTeacher($id: ID!) {
teacher(id: $id) {
id
name
}
}
"""
result = run_graphql_query(query, {"id": teacher_fixture.id})
assert not result.errors
assert result.data == {
"teacher": {
"id": str(teacher_fixture.id),
"name: teacher_fixture.name,
},
} Pros
Cons
Which one to go?Most of people I've discussed this with seem to agree that test client approach is better because it checks not only resolver itself but also that resolver works with schema, child resolvers and error handling. Personally I've started with unit testing just resolver functions, but quickly moved to running test client and testing GraphQL fields because that caught more errors (eg. me breaking error handling by mistake or changing field name on model breaking GraphQL field). Here's example of this approach from my OS project. |
Beta Was this translation helpful? Give feedback.
-
Thanks @rafalp for your quick response. It helped me save my time . I have successfully created tests for my project. |
Beta Was this translation helpful? Give feedback.
-
I am new to GraphQL and this library so i am unable to write tests for my resolvers. I cannot any documentation regarding tests in adriane docs so i have to ask here. I hope someone can write a dummy test for one of my resolver so i will get a start.
Beta Was this translation helpful? Give feedback.
All reactions