Boilerplate for API Automation using Mocha, should.js and supertest.js

The biggest difficulty a novice tester faces while trying to learn new technologies is to find the proper test environment to experiment with.

To learn API automation you need APIs with which you can play around.

Although you will get several open source APIs but most of them are limited to GET requests or give you exposure to fake APIs on which you don’t have much control.

To overcome this issue we are going to create our own fake APIs using json-server.

To install json-server use the command-

npm install -g json-server

Now create a db.json file which will contain the data in JSON format and will act as API end point.A sample content can be-

{ “superhero”: [ { “id”: 1, “name”: “Spiderman”, “fName”: “Peter”, “lName”: “Parker”, “age”: 20, “powers”: [ “wall-crawling”, “web-slinging” ], “killer”: false } ] }

To run the json-server use command(I have defined script fakeApi: json-server — watch db.json inside package.json):

npm run fakeApi

And now you can access your fake APIs using the url http://localhost:3000/superhero and perform all API operations as long as json-server is running.

With every request which causes data modification(PUT,POST and DELETE) your db.json file will keep on saving the changes and thus allowing you to test the changes made.

In the boilerplate, which you can download from https://github.com/shashikumarraja/apiTestingWithMochaBoilerPlate ,I have created test cases to test this API to simulate real world API testing scenarios like-

  1. GET List of superheros and verify data types.
  2. Create(POST) a new superhero and then GET that created superhero and verify data and data types of the field.
  3. Update(PUT) an existing superhero entry and then GET that superhero to assert the updates.
  4. DELETE an existing superhero and then try to GET that superhero to verify deletion operations.

Simply, clone or download the project, traverse inside the project directory, install and run json-server and type below command to run the test suite.

npm test

I have created superheros in db.json. You can go ahead and create supervillains and make superheroes fight with them using APIs. Have a fun learning experience.