Easy way to Automate your APIs using node.js and mocha

Arun M
3 min readSep 24, 2020

--

Forget about RestAssured — you don’t need to convert your JSON objects to Java objects and writing huge lines of code for your pojo classes, with JS validating your apis are much easier and faster.

→ Things you need to get started

  • Node installed in your computer
  • Visual Studio IDE

Lets get Started.. !!!

  • Initialise your project using npm init
  • Add following packages to your dependencies package.json :
    node-fetch → to call your rest apis
    mocha → to run your test suite
    chai → for assertions
    mocha-allure-reporter→ for your test reports
    log4js→ for your test execution logs
package.json
  • Write helper classes by calling node-fetch for following rest api operations
    — GET
    — POST
    — PUT
    — DELETE
example reusable function for making a POST api call
  • Write Test Cases using mocha’s describe() and it() functions.
    — it() refers to your test case
    — describe() refers to your test suite.
    — call your api-wrapper functions to make api
    — validate your responses using chai — here I have used expect
    — here I am comparing the response_code from a test data file and actual response returned from books_api
testdata.json
test.js which contains test cases and test suites

Integrating Reports and Logs

  • Using Allure for creating HTML reports — createStep() method
  • Using Log4js used to log output into .log files— logger.info() method

EXECUTION…!!!!

  • Add test execution command inside scripts.test in your package.json file.
    command : mocha <your_file_name>.js
  • Run Command →npm test

Generating HTML Reports.. :)

allure command : allure generate allure-results — clean -o allure-report && allure open allure-report

Note : Access to full source code is available here.

--

--

Arun M
Arun M

Written by Arun M

Passionate Tester. Quality Engineering. Interested in Technology and Sports.

Responses (4)