Write Negative API Tests
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 -
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