# Empower Your GraphQL API Testing: A Step-by-Step Jest Guide

Are you ready to take your GraphQL API testing to the next level? If you've ever wondered how to test your GraphQL endpoints using Jest effectively, you're in the right place. Testing GraphQL APIs can be challenging due to their unique query language and resolvers, but fear not – Jest is here to simplify the process.

You can fork this GitHub repository ([Repository Link](https://github.com/icon-gaurav/mastering-graphql-with-nodejs/tree/testing-with-jest)) and get along with me step-by-step

Let's dive in and unlock the secrets to effective GraphQL API testing together!

### Installing Jest and required dependencies

```bash
# for typescript
npm install --save-dev ts-jest

# for javascript
npm install --save-dev jest
```

### Configuring Jest for testing

Since we are using typescript, we need to configure our application a little bit

Let's initialize the jest using the command

```bash
npx ts-jest config:init
```

This will generate a ***<mark>jest.config.js</mark>*** file. This is what makes jest to work with typescript.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709574944290/21268ed1-7e64-4cdd-8095-b394e22222ec.png align="center")

### Writing Test cases

Let's create a file named ***<mark>createPost.test.ts</mark>*** in the ***<mark>tests</mark>*\***\* directory.

Then import the ***@jest/globals*** library, which has the required functions to test.

```typescript
import {describe, expect, test} from '@jest/globals';
import {GraphQLClient} from 'graphql-request';
```

We need a graphql client to execute the graphql query and get the response to compare the expected result. We are going to use the '***graphql-request***' library for that

```typescript
import {GraphQLClient} from 'graphql-request';

// create a new graphql client for requesting to our api
const client = new GraphQLClient("http://localhost:4000/")
```

Let's define what we are going to test in this example.

In this example, we are going to test the ***createPost*** mutation in which we first create the post using our API and then check whether it has the same title as the post or not

```typescript
describe('create post mutation', () => {

    test('creates a new post', async () => {

        // graphql query
        const query = `#graphql 
        mutation CREATE_POST_TEST($title: String!, $content: String) {
            createPost(title: $title, content: $content) {
                _id
                content
                content
                title
            }
        }
        `;

        // query variables
        const variables = {
            "title": "testing post title",
            "content": "testing post content"
        };

        let data: any = {};

        try {
            // execute the query
            data = await client.request(query, variables);

        } catch (e) {
            // report the error
            console.log(e)
        }

        expect(data?.createPost).toHaveProperty("title", variables?.title)

    });

});
```

In the above code

1. We use ***<mark>describe</mark>*** to describe a unit test suite. Even though it's not required, it's helpful to understand what this test suite is all about.
    
2. In the ***<mark>test</mark>***, we write the test code. The first argument of this function tells about what this test case is all about and the second argument is a callback function that contains the test code
    
3. In the callback function first, we sent the API request and then compared the actual and expected responses. The test passes if both match otherwise it fails.
    

### Execute the test cases

There are two steps in executing the test cases

1. Start the API server
    

```bash
npm run start:dev
```

2. Run jest to execute all of the test cases
    

```bash
jest
```

### Output

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1709576704056/6ec50537-8fb9-4814-be65-3540f72a8b48.png align="center")

With Jest's help, we've learned how to set up a killer testing environment, write top-notch test cases, and integrate testing seamlessly into our workflow. So, let's keep that testing momentum going and deliver some seriously reliable and resilient APIs to our users! Ready to level up? Let's do this!
