Image for post
Image for post
https://www.youtube.com/watch?v=NXorgale-hE

In this post, we’ll take a look at some other ways to optimize our test. We will create a new config file to store configuration related data as well as use faker.js to randomize test data.

Configuration file

Instead of storing URLs and other configuration related within our tests file, we can create a config file and store data there and import it directly in our tests. This will help clean up our tests and make it easier to read. Even something as simple as this works:

export default {
baseUrl: 'https://gorest.co.in/public-api/',
// ... other config data
};

Randomizing test data

Instead of hardcoding test data, we can use external libraries such as faker.js to help generate random test data for us. To use faker, import the package using npm install faker and then start using it…


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. …


Image for post
Image for post
https://youtu.be/HzARztpOW7s

In this post, I will cover how async-awaits can help us write better and clean tests. async-await makes working with asynchronous programming a bit easier for us, let's see how it works -

Async-Await

async functions and await keywords were introduced in ECMAScript 2017 edition. When you pass a async keyword to a function, it returns a promise. And, the await keyword waits for the promise to be fulfilled before moving on to the next step.

So how does it relate to our API tests? Well, let’s take a look at an example. We’ll write a test to create a user post, this test will first create a user and then use the userId to create a post. …


Image for post
Image for post
https://youtu.be/Bz77JGEKRrk

So far in the previous posts, we wrote a few API tests for various HTTP methods and we were relying on the data that already existed on our test site. The challenge with that is if the existing data changes or gets removed it’ll end up breaking our tests. Let’s take a look at how we can fix that.

Current test structure

This is how the tests have been structured so far:

// GET Tests - uses existing userId to get the user data
// POST Test - creates a new user
// PUT Test - uses existing userId to update the user data
// DELETE Test - uses existing userId to delete the user…

Image for post
Image for post

The HTTP DELETE method is pretty straightforward, it deletes an existing resource and if the resource is already deleted it will most likely throw a ‘not found’ error.

Let’s take a look at an example -

it('DELETE /users/:id', () => {
return request
.delete('users/2')
.set('Authorization', `Bearer ${TOKEN}`)
.then((res) => {
expect(res.body.data).to.be.eq(null);
});
});

This will likely return the body similar to this-

{ code: 204, meta: null, data: null }

And, upon hitting the same request again, you will see a not-found error -

{ code: 404, meta: null, data: { message: 'Resource not found' } }

Check out this video to see a detailed explanation of how to work with the HTTP DELETE 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


Image for post
Image for post
https://youtu.be/d2mGuL4VlgA

Similar to the HTTP POST method, the HTTP PUT method also takes in the request payload but instead of creating a new resource, it lets the user update the existing resource.

The difference between the PUT and POST method is that PUT is idempotent i.e you can keep calling the same request multiple times but it won't have any side effects, unlike a POST request.

Let’s take a look at an example of a PUT request below -

it('PUT /users/:id', () => {
// data to update
const data = {
status: 'Active',
name: `Luffy - ${Math.floor(Math.random() * 9999)}`,
};
return request
.put('users/132')
.set('Authorization', `Bearer ${TOKEN}`)
.send(data)
.then((res) => {
expect(res.body.data).to.deep.include(data); …

Image for post
Image for post
https://youtu.be/CuTLcnSna2E

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

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); …

Image for post
Image for post
https://youtu.be/VrsMlnX6pUY

Let’s take a look at how to write API tests using JavaScript for the HTTP GET method.

So in the previous post, we wrote a basic GET test to get us started, and now we’ll take a step further and write a couple more of GET tests to get a good understanding of them.

Accessing an individual resource

In this test, we’ll try to access data for an individual user.

// access the user data based on the id provided
it('GET /users/:id', () => {
return request.get(`users/1?access-token=${TOKEN}`).then((res) => {
// validate the data being returned is of the expected user
expect(res.body.data.id).to.be.eq(1);
});
});

Working with query parameters

Sometimes, you need to provide query params to filter out the data being requested. …


Image for post
Image for post
https://youtu.be/TTyl1psI4DE

In this post, we’ll take a look at what tools/technologies do we need for writing API tests using JavaScript and then we’ll also write our first API test. So let’s get started…

⚙️ Dependencies:

First off, we’ll need to get the following dependencies installed to set up our base framework -

Note: the above libraries/frameworks are optional to use, you can replace any one or all of them to meet your desired goals. …


Image for post
Image for post
https://youtu.be/JTReLAmB18c

To do API automation testing with JavaScript, we’ll first need to know which libraries or frameworks we can use that’ll help build our test framework.

Since we are doing API testing, we’ll need some way to make HTTP calls programmatically and for that, we will be
using the SuperTest npm package.

SuperTest

SuperTest is built on top of SuperAgent which basically allows you to make HTTP requests and SuperTest provides a high-level abstraction for testing those HTTP requests. Let’s take a look at an example:

const request = require('supertest'); request()
.get('/user') // access user route
.expect('Content-Type', /json/) // verify the content type
.expect('Content-Length', '15')
.expect(200) // verify the status code
.end(function(err, …

About

Automation Bro

I enjoy discussing topics related to Test Automation | Quality Assurance | Web Dev. Check out my Youtube channel — AutomationBro

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