Write Negative API Tests

Image for post
Image for post
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");
});

You can also clone the GitHub repo to access this code

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store