Nodejs Api request for cucumber test cases

To test the Nodejs API so please create the API in Nodejs.

Suppose you created a customer register API.


http://127.0.0.1:3333/api/register

Now, pass the requested data


   {  
         "first_name":"John",
	 "last_name":"Taylor",
	 "email":"john@gmail.com",
	 "password":"john123",
	 "cpass":"john123"
   }

Where first_name, last_name, email, password and cpass are request parameters.

Now, get the response


{  
    "status": 200,
    "message": "Customer Registered successfully."
}

To write the Cucumber test cases for Nodejs API in through the below steps

1) Firstly create a features folder in the root folder of your Nodejs project.

2) Now create the file name create_customer_via_jsonfile.feature extension and write the below code in this


# Create Customer API Testing Exercise via json file
Feature: Create new customer signup through json file
 Call API to create new customer through json file

  Scenario: Create new customer through json file
  
  Given create new customer through json file and data are
   """
   {  
         "first_name":"John",
	 "last_name":"Taylor",
	 "email":"john@gmail.com",
	 "password":"john123",
	 "cpass":"john123"
   }
  """

  When I send URL through POST method for JSON file http://127.0.0.1:3333/api/register

  Then response data is 
  """
  {  
    "status": 200,
    "message": "Customer Registered successfully."
   }
  """

  

in the create_customer_via_jsonfile.feature file, you have to create Feature: feature_name after that create the Scenario: scenario_name
after that, you have to create 3 steps
Given:- It is used for request data
When:- it is used for the condition
Then:- It is used for response data

3) Now create the create_customer_via_jsonfile_step folder and create create_customer_via_jsonfile_step.jsfile into this and put the below code.


// features/support/steps.js
const { Given, When, Then } = require("cucumber");
const assert = require("assert")
const got = require('got');

var output;
var jsonfile_body_request;


Given(/^create new customer through json file and data are$/, async function(request_data){
  jsonfile_body_request=request_data;
});

When('I send url through POST method for json file {}', async function(url) {

  const {body} = await got.post(url, {
		json: JSON.parse(jsonfile_body_request),
		responseType: 'json'
	});

  output={  
  "status": (body.status),
  "message": body.message
  }


});

Then(/^response data is$/, async function (expected_output) {
  var main_expected_output= JSON.parse(expected_output);
  assert.equal(JSON.stringify(output), JSON.stringify(main_expected_output));
});


4) Now, run the test cases


./node_modules/.bin/cucumber-js

Now, check the results and found the 1 scenarios, and 3 steps are passed.