DEV Community

Cover image for Write API tests for HTTP POST method
Dilpreet Johal
Dilpreet Johal

Posted on

Write API tests for HTTP POST method

Let's take a look at how to write API tests using JavaScript for HTTP POST methods.

So when working with the POST method, one of the key things to remember is to send the request data along with the request. Let's take a look at an example of creating a new user using the POST method -

it('POST /users', () => {
   // data to send with the request
    const data = {
      email: `test-${Math.floor(Math.random() * 9999)}@mail.ca`,
      name: 'Test name',
      gender: 'Male',
      status: 'Inactive',
    };

    return request
      .post('users') // hitting the POST route
      .set('Authorization', `Bearer ${TOKEN}`) // setting token for authentication
      .send(data)
      .then((res) => {
        // validate the entire response data using Chai assertion
        expect(res.body.data).to.deep.include(data);
      });
  });

Enter fullscreen mode Exit fullscreen mode

So the above code will create a new user for us and will give a similar response back -

{
  code: 201,
  meta: null,
  data: {
    id: 1437,
    name: 'Test name',
    email: 'test-6243@mail.ca',
    gender: 'Male',
    status: 'Inactive',
    created_at: '2020-09-27T04:15:02.057+05:30',
    updated_at: '2020-09-27T04:15:02.057+05:30'
  }
}

Enter fullscreen mode Exit fullscreen mode

There you go, that's all we need to do to create an API test for HTTP POST method. 🙌

Check out this video to see a detailed explanation on how to work with HTTP POST method:

You can also clone the GitHub repo 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&ab_channel=AutomationBro


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

Happy testing! 😄

...

Subscribe to my YouTube channel
Support my work - https://www.buymeacoffee.com/automationbro
Follow @automationbro on Twitter

Top comments (2)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Oh cool I did not know about gorest.co.in/ do you use Insomnia and Postman?

Collapse
 
dilpreetjohal profile image
Dilpreet Johal

Yeah, gorest.co.in/ is a great site if you need to quickly test out some apis.
And, I use Postman mainly for manual API tesing, never tried Insomnia.