File: unit-testing.md

package info (click to toggle)
strawberry-graphql-django 0.62.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,968 kB
  • sloc: python: 27,530; sh: 17; makefile: 16
file content (63 lines) | stat: -rw-r--r-- 1,686 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
---
title: Unit Testing
---

# Unit testing

Unit testing can be done by following the
[strawberry's testing docs](https://strawberry.rocks/docs/operations/testing) reference.

This lib also provides a `TestClient` and an `AsyncTestClient` that makes it easier
to run tests by mimicing a call to your API.

For example, suppose you have a `me` query which returns the currently logged in
user or `None` in case it is not authenticated. You could test it like this:

```python
from strawberry_django.test.client import TestClient


def test_me_unauthenticated(db):
    client = TestClient("/graphql")
    res = client.query("""
      query TestQuery {
        me {
          pk
          email
          firstName
          lastName
        }
      }
    """)
    assert res.errors is None
    assert res.data == {"me": None}


def test_me_authenticated(db):
    user = User.objects.create(...)
    client = TestClient("/graphql")

    with client.login(user):
        res = client.query("""
          query TestQuery {
            me {
              pk
              email
              firstName
              lastName
            }
          }
        """)

    assert res.errors is None
    assert res.data == {
        "me": {
            "pk": user.pk,
            "email": user.email,
            "firstName": user.first_name,
            "lastName": user.last_name,
        },
    }
```

For more information how to apply these tests, take a look at the [source](https://github.com/strawberry-graphql/strawberry-django/blob/main/strawberry_django/test/client.py) and [this example](https://github.com/strawberry-graphql/strawberry-django/blob/main/tests/test_permissions.py#L49)