Sending request using a token with node.js

Hey guys, today I will post about how to use a token when sending your requests in node.js. As I am using these requests for my automated tests with cucumber.js, I am going to post the step definition, too.

 

The class with the API requests:

 

'use strict';

var request = require('sync-request');
var protractor = require('protractor');
var browser = protractor.browser;
var sprintf = require('sprintf-js').sprintf;

function API() {

 //Initialise the variables
 var token = null;
 var total = null;
 var id = null;

 return {
  //Authenticate request where it gets the token to be used after
   authenticate: function() {
   var response = request('POST', getAuthURL(), {
   headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
   },
   body: getAuthBody()
 });

 var json = parseResponse(response);
 if (response.statusCode !== 200) {
  throw Error('Unable to authenticate: ' + response.statusCode);
 }

 token = json.token_auth;
 console.log('Authenticated with token:[' + token + ']');

 return token;
 },

 //Get the token from the authenticate request
 create: function() {
  var response = request('GET', getCreateURL(), {
  headers: {
  'Content-Type': 'application/json',
  'Auth-Token': token
  },
  body: getCreateBody()
 });

   var json = parseResponse(response);
   if (response.statusCode !== 200) {
    throw Error('Unable to create:' + response.statusCode);
   }

   //Get the nodes from the response, data is an array
   total = json.total;
   id = json.data[0].id;
   console.log(id);
   console.log('Created:[' + total + ']');

    return json;
   },

   //Parsing the response
   function parseResponse(response) {
    return JSON.parse(response.getBody('utf8'));
   },

   //Returning the body with the credentials from protractor.js config
   function getAuthBody(response) {
    return 'user=' + browser.params.credentials.username +
 '&pass=' + browser.params.credentials.password;
   },

   //Write the body to create the user and convert it
   function getCreateBody(response) {
   return JSON.stringify({
    deviceId: '123456789',
    name: 'Rafaela',
    description: 'Description',
    cities: [{
     'label': 'London'
    }, {
     'label': 'Oxford'
    }]
   });
 },

   //Get address and then endpoint from the protractos.js
   function getAuthURL() {
    return getPath() + '/' + browser.params.endpoints.authenticate;
   },

   //Get the host and path, easier to maintain
   function getPath() {
    return browser.params.host + '/' + browser.params.path;
   },

   function getCreateURL() {
    return getPath() + '/' + browser.params.endpoints.create;
   }

}

module.exports = API;

 

  • Authenticate request where it’s getting the token to be used in the Create request.

 

Your protractor.js with protractor and cucumber configs:

'use strict';

 var os = require('os');
 var platform = os.platform();

 //Browsers that you will run the automation
 var chrome = {
  browserName: 'chrome'
 };

 var safari = {
  browserName: 'safari'
 };

 var firefox = {
  browserName: 'firefox'
 };

 var capabilities = [chrome];

 // Enable Safari only on macos
 if (platform === 'darwin') {
 capabilities.push(safari);
 }

exports.config = {
 seleniumAddress: 'http://127.0.0.1:4444/wd/hub',
 //Point to the features path
 specs: [
 'src/features/*.feature'
 ],
 multiCapabilities: capabilities,
 noGlobals: true,
 baseUrl: 'http://localhost:5000/',
 framework: 'custom',
 frameworkPath: require.resolve('protractor-cucumber-framework'),
 cucumberOpts: {
 //Point to the step definitions and support classes
 require: 'test/steps/**/*.js',
 //Format for the cucumber report
 format: [
 'json:test-reports/cucumber-json/cucumber.json',
 'pretty'
 ],
 strict: true,
 //Tags filtering the scenarios
 tags: [
  '@regressionTests',
  '~@pending'
  ]
 },
 //Params to pass to your tests, username, passwords, etc.
 params: {
  credentials: {
   username: 'user',
   password: 'Password123'
  }
 },
 //Your site address
 host: 'http://www.testSite.com',
 //Path to use in the requests
 path: 'rest',
 //Endpoints for the requests
 endpoints: {
   authenticate: 'auth',
   create: 'create/user'
  }
 }
}
};

 

Your step definition with the step and calling the api functions:

'use strict';

var API = require('../api');

 var SupportSteps = function() {

 var api = new API();

 this.Given(/^I have created the user$/, function() {
       //Calling the authenticate first, you will get the token to use it
       api.authenticate();
       api.create();
     });
 };

module.exports = SupportSteps;

  • So here, you have the step definition that calls the functions to authenticate first and then to create the user after using the token.

Thank you guys ! See you next weekend 🙂

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: