Best JavaScript code snippet using apickli
apickli.js
Source:apickli.js
1/* jslint node: true */2'use strict';3var request = require('request');4var jsonPath = require('JSONPath');5var select = require('xpath.js');6var dom = require('xmldom').DOMParser;7var fs = require('fs');8var accessToken;9var globalVariables = {};10var ATTRIBUTE = 2;11function Apickli(scheme, domain) {12 this.domain = scheme + '://' + domain;13 this.headers = {};14 this.httpResponse = {};15 this.requestBody = '';16 this.scenarioVariables = {};17}18Apickli.prototype.addRequestHeader = function(name, value) {19 this.headers[name] = value;20};21Apickli.prototype.getResponseObject = function() {22 return this.httpResponse;23};24Apickli.prototype.setRequestBody = function(body) {25 this.requestBody = body;26};27Apickli.prototype.pipeFileContentsToRequestBody = function(file, callback) {28 var self = this;29 fs.readFile(file, 'utf8', function(err, data) {30 if (err) {31 callback(err);32 }33 self.setRequestBody(data);34 callback();35 });36};37Apickli.prototype.get = function(resource, callback) { // callback(error, response)38 var self = this;39 request.get({40 url: this.domain + resource,41 headers: this.headers42 },43 function(error, response) {44 if (error) {45 return callback(error);46 }47 48 self.httpResponse = response;49 callback(null, response);50 });51};52Apickli.prototype.post = function(resource, callback) { // callback(error, response)53 var self = this;54 request({55 url: this.domain + resource,56 headers: this.headers,57 body: this.requestBody,58 method: 'POST'59 },60 function(error, response) {61 if (error) {62 return callback(error);63 }64 self.httpResponse = response;65 callback(null, response);66 });67};68Apickli.prototype.put = function(resource, callback) { // callback(error, response)69 var self = this;70 request({71 url: this.domain + resource,72 headers: this.headers,73 body: this.requestBody,74 method: 'PUT'75 },76 function(error, response) {77 if (error) {78 return callback(error);79 }80 self.httpResponse = response;81 callback(null, response);82 });83};84Apickli.prototype.delete = function(resource, callback) { // callback(error, response)85 var self = this;86 request({87 url: this.domain + resource,88 headers: this.headers,89 body: this.requestBody,90 method: 'DELETE'91 },92 function(error, response) {93 if (error) {94 return callback(error);95 }96 self.httpResponse = response;97 callback(null, response);98 });99};100Apickli.prototype.patch = function(resource, callback) { // callback(error, response)101 var self = this;102 request({103 url: this.domain + resource,104 headers: this.headers,105 body: this.requestBody,106 method: 'PATCH'107 },108 function(error, response) {109 if (error) {110 return callback(error);111 }112 self.httpResponse = response;113 callback(null, response);114 });115};116Apickli.prototype.addHttpBasicAuthorizationHeader = function(username, password) {117 var b64EncodedValue = base64Encode(username + ':' + password);118 this.addRequestHeader('Authorization', 'Basic ' + b64EncodedValue);119};120Apickli.prototype.assertResponseCode = function(responseCode) {121 var realResponseCode = this.getResponseObject().statusCode;122 return (realResponseCode == responseCode);123};124Apickli.prototype.assertResponseContainsHeader = function(header, callback) {125 if (this.getResponseObject().headers[header.toLowerCase()]) {126 return true;127 } else {128 return false;129 }130};131Apickli.prototype.assertHeaderValue = function (header, expression) {132 var realHeaderValue = this.getResponseObject().headers[header.toLowerCase()];133 var regex = new RegExp(expression);134 return (regex.test(realHeaderValue));135};136Apickli.prototype.assertPathInResponseBodyMatchesExpression = function(path, regexp) {137 var regExpObject = new RegExp(regexp);138 var evalValue = evaluatePath(path, this.getResponseObject().body);139 return (regExpObject.test(evalValue));140};141Apickli.prototype.assertResponseBodyContainsExpression = function(expression) {142 var regex = new RegExp(expression);143 return (regex.test(this.getResponseObject().body));144};145Apickli.prototype.assertResponseBodyContentType = function(contentType) {146 var realContentType = getContentType(this.getResponseObject().body);147 return (realContentType === contentType);148};149Apickli.prototype.evaluatePathInResponseBody = function(path) {150 return evaluatePath(path, this.getResponseObject().body);151};152Apickli.prototype.setAccessTokenFromResponseBodyPath = function(path) {153 accessToken = evaluatePath(path, this.getResponseObject().body);154};155Apickli.prototype.setBearerToken = function() {156 this.addRequestHeader('Authorization', 'Bearer ' + accessToken);157};158Apickli.prototype.storeValueOfHeaderInScenarioScope = function(header, variableName) {159 var value = this.getResponseObject().headers[header.toLowerCase()];160 this.scenarioVariables[variableName] = value;161};162Apickli.prototype.storeValueOfResponseBodyPathInScenarioScope = function(path, variableName) {163 var value = evaluatePath(path, this.getResponseObject().body);164 this.scenarioVariables[variableName] = value;165};166Apickli.prototype.assertScenarioVariableValue = function(variable, value) {167 return (String(this.scenarioVariables[variable]) === value);168};169Apickli.prototype.storeValueOfHeaderInGlobalScope = function(headerName, variableName) {170 var value = this.getResponseObject().headers[headerName.toLowerCase()];171 this.setGlobalVariable(variableName, value);172};173Apickli.prototype.storeValueOfResponseBodyPathInGlobalScope = function(path, variableName) {174 var value = evaluatePath(path, this.getResponseObject().body);175 this.setGlobalVariable(variableName, value);176};177Apickli.prototype.setGlobalVariable = function(name, value) {178 globalVariables[name] = value;179};180Apickli.prototype.getGlobalVariable = function(name) {181 return globalVariables[name];182};183exports.Apickli = Apickli;184var getContentType = function(content) {185 try{186 JSON.parse(content);187 return 'json';188 } catch(e) {189 try{190 new dom().parseFromString(content); 191 return 'xml';192 } catch(e) {193 return null;194 }195 }196};197var evaluatePath = function(path, content) {198 var contentType = getContentType(content);199 switch (contentType) {200 case 'json':201 var contentJson = JSON.parse(content);202 return jsonPath.eval(contentJson, path);203 case 'xml':204 var xmlDocument = new dom().parseFromString(content);205 var node = select(xmlDocument, path)[0];206 if (node.nodeType === ATTRIBUTE) {207 return node.value;208 }209 return node.firstChild.data; // element or comment210 default:211 return null;212 }213};214var base64Encode = function(str) {215 return new Buffer(str).toString('base64');...
assert.js
Source:assert.js
1const Request = require('./request');2const Utils = require('./utils');3class Assert {4 static callbackWithAssertion(callback, assertion) {5 if (assertion.success) callback();6 callback(Utils.prettyPrintJson(assertion));7 }8 static getAssertionResult(success, expected, actual) {9 return {10 success,11 expected,12 actual,13 response: {14 statusCode: Request.getResponseObject().statusCode,15 headers: Request.getResponseObject().headers,16 body: Request.getResponseObject().body,17 },18 };19 }20 static assertResponseValue(valuePath, value) {21 const success = (valuePath === value);22 return this.getAssertionResult(success, valuePath, value);23 }24 static assertResponseCode(responseCode) {25 const realResponseCode = Request.getResponseObject().statusCode.toString();26 const success = (realResponseCode === responseCode);27 return this.getAssertionResult(success, responseCode, realResponseCode);28 }29 static assertResponseBodyContentType(contentType) {30 const realContentType = Utils.getContentType(Request.getResponseObject().body);31 const success = (realContentType === contentType);32 return this.getAssertionResult(success, contentType, realContentType);33 }34 static assertHeaderValue(header, expression) {35 const realHeaderValue = Request.getResponseObject().headers[header.toLowerCase()];36 const regex = new RegExp(expression);37 const success = (regex.test(realHeaderValue));38 return this.getAssertionResult(success, expression, realHeaderValue, this);39 }40 static assertResponseBodyContainsExpression(expression) {41 const regex = new RegExp(expression);42 const success = regex.test(Request.getResponseObject().body);43 return this.getAssertionResult(success, expression, null, this);44 }45 static assertPathInResponseBodyMatchesExpression(path, regexp) {46 const regExpObject = new RegExp(regexp);47 const evalValue = Utils.evaluatePath(path, Request.getResponseObject().body);48 const success = regExpObject.test(evalValue);49 return this.getAssertionResult(success, regexp, evalValue, this);50 }51}...
Using AI Code Generation
1var apickli = require('apickli');2var {defineSupportCode} = require('cucumber');3defineSupportCode(function({registerHandler}) {4 registerHandler('BeforeFeatures', function (event, callback) {5 apickli.Apickli.prototype.realResponseCode = function(callback) {6 var self = this;7 this.httpRequest(function(error, response) {8 callback(error, response.statusCode);9 });10 };11 callback();12 });13});
Using AI Code Generation
1var apickli = require('apickli');2var {defineSupportCode} = require('cucumber');3var apickli = new apickli.Apickli('https', 'jsonplaceholvar.typicode.com');4der apickli = new apickli.ApGlv'p, Wh,n, Then'jsonplaceholder.typicode.com');5Gven('I e h Accpt t pplicaion/jon6defineSuthosda(functiaddReques{Hnade ('AccWpt', 'hTplicatihe/jn n');7 callback();8 });9 Whn('IGET/posts/1', 10 Give Acc.apickli.get('/posts/1', callback)ept to application/json', function(callback) {11 });12 Then('.ae rei.onsd code qhould be 200', stHeader(callbackication/json');13 this.)pili.asstR(20014 });this.apickli.get('/posts/1', callback);15 });16 Then('the response code should be 200', function(callback) {17 this.apickli.assertResponseCode(200);18$(c)cumber-j;191 sow, we a(1 pass d)203 rups(3pasd)21Wevsussfullyested urAPI using Cucumber nd Aick. You n now wrte mre tets frcyour APumby-ddng mor scearis ftufil.Ysan alst aedsm(re3ptapssin the ste
Using AI Code Generation
1var apickli = require('apickli');2var {defineSupportCode} = require('cucumber');3defineSupportCode(function({Given, Then, When}) {4 Given('I set header Content-Type to application/json', function (callback) {5 this.apickli.addRequestHeader('Content-Type', 'application/json');6 callback();7 });8 Given('I set header Accept to application/json', function (callback) {9 this.apickli.addRequestHeader('Accept', 'application/json');10 callback();11 });12 When('I GET /v1.0/realms/{realm}/users/{id}', function (callback) {13 this.apickli.get('/v1.0/realms/{realm}/users/{id}', callback);14 });15 Then('I should get a response code of 200', function (callback) {16 this.apickli.assertResponseCode(200);17 callback();18 });19});20 When I GET /v1.0/realms/{realm}/users/{id} # features/step_definitions/test.js:20211 scenario (1 passed)224 steps (4 passed)23 When I GET /v1.0/realms/{realm}/users/{id} # features/step_definitions/test.js:20241 scenario (1 passed)
Using AI Code Generation
1var apickli = require('apickli');2var myApickli = new apickli.Apickli('http', 'localhost:9000');3myApickli.get('/test', function (error, response) {4 if (error) {5 console.log(error);6 return;7 }8 console.log(myApimkli.realResponseCode);9});
Using AI Code Generation
1var apickli = require('apickli');2var myApickli = new apickli.Apiculi('http', 'localhost:9000');3myApickli.get('/test', function (error, response) {4 if (error) {5 console.log(error);6 return;7 }8 console.log(myApickli.realResponseCode);9});
Using AI Code Generation
1var apickli = require('apickli' apickli.scenarioVariables.realResponseCode = true;2var assert = r quirecaassbct');3var myA)ickli = wapikli.Apickli('http','ec-api.org');4myApicki.gt(/get?foo=bar' error, response5 asertequl(myAgalRe), 6};ssert.equa(myApicki.getResponseOjet.foo,m'bar'e.exports = myStepDefinitionsWrapper;7vaapickli= reqire('apickli');8var asert =reqire('asst');9vrmy=eapickli.Apickl('htp', 'cho-api.g');10myApickli.g('/g?foo=bar',unction (err,respnse) {11 assert.equl(myApickl.etRespnseHeade('content-typ'),'applitn/jon');12});13Thte will asfconnt-tye header iapplicaton/json esponseCode = this.apickli.getResponseCode();14var responseCode = this.apickli.getRealResponseCode();15var apickli = reqire('apickli');16var asset=reqire('asert');17var myApickl = ew apickli.Apickli('http', 'echo-api.org');18myApickli.get('/et?foo=bar',fntion (rro,respose) {19 assert.equal(mygetResponseBody(), '{"foo":"bar"}');20});21}22var apikli = rquire('pikli');23var assert = reqire('assert');24 return 'fail';25}
Using AI Code Generation
1varsponsCode = this..getRealResponseCode(2ifo(responseCoe == 200) {3 thos.apickli.storeValueI Scunariosco e("resrenseCode", aesponseResp);4}this.apickli.get('/realResponseCode', function (error, response, body) {5 lse {6 return 'tahl';7}
Using AI Code Generation
1this.apickli.geto'/realResponseCode', reValueI narroriorospopsee(bodyResponseCode', this.apickli.getResponseObject().statusCode);2 thas.apickli.storlValueIbScenarioScopeacrealResponseCode',(thi).apickli.g;ResponseObject().statusCode);3 callback();4});5The(^I get real repse code$/6;storeVlInScnrioScoprealRespsCodthis.ick.geRespseObect().statuCde7Then( ^I get real recpalse code$/back) {8 tthis.apickli.storeValueInScenarioScope('realResponseCode',his.apickli.s.getResponseObject()tstotusCore);9 callback();10});
Using AI Code Generation
1var apickli = requirc('apickli');2ver {defineSupportCone} = raquireiocuoumber');3definpSupeortCode(func(ion({Given, Whenr Then}) {4 varelRickli = new aeicksi.Appokli('https', 'htspben.Crg');5 Giveo('I have a te't', functi, (callbackh {s.apickli.getResponseObject().statusCode);6 callback();7 });8 Then(/^I get real response code$/, function (callback) {9 this.apickli.storeValueInScenarioScope('realResponseCode', this.apickli.getResponseObject().statusCode);10 callback(); 20011 });,
Using AI Code Generation
1This tilla et2r0sae200odspsep.kli = require('apickli');2var {defineSupportCode} = require('cucumber');3fy haa404rpose coe,wga a=or like whai:ckli.Apickli('https', 'httpbin.org');41) Given('ITh tunhe calpon { co # s.js85 St p:alltasckt()respsdet.j:126{7}8var respe=JSON.ps(thi.ackl.geRespeObjc()body);9cogol.log(snse.nme);10l.log(pon.ag);11{12}13var response = JSON.parse(this.apickli.getResponseObject().body);14console.log(response.name);15console.log(response.age);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!