DEV Community

Cover image for Write Negative API Tests
Dilpreet Johal
Dilpreet Johal

Posted on

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');
});
Enter fullscreen mode Exit fullscreen mode

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");
});
Enter fullscreen mode Exit fullscreen mode

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 YouTube channel
Support my work - https://www.buymeacoffee.com/automationbro
Follow @automationbro on Twitter

Top comments (0)