Using Async-Await with SuperTest
Tags: javascript, testing, api, tutorial
Published: 2020-10-18 15:01:22

In this post, I will cover how `async-awaits` can help us write better and clean tests. `async-await` makes working with asynchronous programming a bit easier for us, let's see how it works - 

#### Async-Await
`async` functions and `await` keywords were introduced in ECMAScript 2017 edition. When you pass an `async` keyword to a function, it returns a `promise`. And, the `await` keyword waits for the `promise` to be fulfilled before moving on to the next step. 

So how does it relate to our API tests? Well, let's take a look at an example. We'll write a test to create a user post, this test will first create a user and then use the `userId` to create a post. 
```javascript
 it('/posts', () => {
    // create user
    request
      .post('users')
      .set('Authorization', `Bearer ${TOKEN}`)
      .send(data)
      .then((res) => {
        expect(res.body.data).to.deep.include(data);
        userId = res.body.data.id;

        // create post using the above userId
        request
          .post('posts')
          .set('Authorization', `Bearer ${TOKEN}`)
          .send(data)
          .then((res) => {
            expect(res.body.data).to.deep.include(data);
          });
      });
  });
```
Instead of creating that massive chain and callbacks like the way we did above, we can instead use `async-await` to make it look a bit cleaner - 
```javascript
// create async function with 'it' block
  it('/posts', async () => {
    // use await to fulfill the promise and get response
    const userRes = await request
      .post('users')
      .set('Authorization', `Bearer ${TOKEN}`)
      .send(data);
    expect(userRes.body.data).to.deep.include(data);
    userId = res.body.data.id;

    // do the same for post request too
    const postRes = await request
      .post('posts')
      .set('Authorization', `Bearer ${TOKEN}`)
      .send(data);

    expect(postRes.body.data).to.deep.include(data);
  });
```
With the help of `async-await`, we are making the code look synchronous where it'll do one thing, complete that and then move to another task. To make it even cleaner, we can create an `async` function for the user generation and call it like this -
```javascript
userId = await createRandomUser();
```
#### To see a detailed explanation of the code above along with other optimization tips, check out the video below:

{% youtube hWGu7qJkoaA%}

You can also clone the [GitHub repo](https://github.com/dilpreetj/JavaScript-API-Automation-Tests) to access this code

***

#### To learn more about API testing, check out my free tutorial series here - 
https://www.youtube.com/watch?v=ZSVw3TyZur4&list=PL6AdzyjjD5HDR2kNRU2dA1C8ydXRAaaBV&
***

I hope this post helped you out, let me know in the comments below! 

Happy testing! 😄 

...

Subscribe to my [YouTube](https://www.youtube.com/channel/UCjugV5pnY6WjvTGYm7U1ucg?sub_confirmation=1) channel
Support my work - https://www.buymeacoffee.com/dilpreetjohal
Follow [@sdetunicorns](https://twitter.com/sdetunicorns) on Twitter

---

#### Enjoyed this read? Discover more insightful articles on software testing and development on my [blog](https://sdetunicorns.com/blog). 🌐