Write Negative API Tests

Dilpreet Johal
Nov 18, 2020

--

https://youtu.be/SUz1_vhqLkY

So far we have written all the positive/happy path test scenarios, in this post, we’ll take a look at how we can write a few negative API tests to ensure our APIs are secure and functioning as they should.

Let’s take a look at some examples -

Unauthenticated Test
Create a test to ensure the user cannot hit the APIs without being properly authenticated.

it('401 Authentication Failed', async () => {
// sending request without the Authentication Token
const postRes = await request.post('posts').send(data);
expect(postRes.body.code).to.eq(401);
expect(postRes.body.data.message).to.eq('Authentication failed');
});

Validation Failed
Create a test to ensure the user should not be able to create data without passing in the required fields.

it('422 Validation Failed', async () => {
// 'body' is a required field which is not being passed with the data
const data = {
user_id: userId,
title: 'My title',
};
const postRes = await request
.post('posts')
.set('Authorization', `Bearer ${TOKEN}`)
.send(data);
expect(postRes.body.code).to.eq(422);
expect(postRes.body.data[0].field).to.eq('body');
expect(postRes.body.data[0].message).to.eq("can't be blank");
});

Check out this video to see how to implement the above test scenarios:

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 mailing list to get access to more content like this
👍 Follow @automationbro on Twitter for the latest updates

--

--

Dilpreet Johal
Dilpreet Johal

Written by Dilpreet Johal

SDET Architect | YouTuber | Tech Blogger | Love to explore new tools and technologies. Get access to all the courses— https://sdetunicorns.com/

No responses yet