Best JavaScript code snippet using ng-mocks
Contractium.test.js
Source:Contractium.test.js
1const BigNumber = web3.BigNumber;2const ContractiumToken = artifacts.require('./ContractiumToken.sol')3contract('ContractiumToken', function (accounts) {4 const owner = accounts[0];5 6 beforeEach(async function () {7 // isolated contract instance8 instanceDefault = await ContractiumToken.new(); 9 });10 it("should have 18 decimal places", async () => {11 const decimals = await instanceDefault.decimals();12 assert.equal(decimals, 18);13 });14 it("should have an initial owner balance of 3 billion tokens", async () => {15 const ownerBalance = (await instanceDefault.balanceOf(owner)).toNumber();16 assert.equal(ownerBalance, 3e+27, "the owner balance should initially be 3 billion tokens");17 });18 // it("shoud allow offering when init contract", async () => {19 // let offeringEnabled = await instanceDefault.offeringEnabled();20 // assert.equal(offeringEnabled, true);21 // });22 // it("should have an initial offering allowance of 900 million tokens", async () => {23 // let currentTotalTokenOffering = await instanceDefault.currentTotalTokenOffering();24 // let currentTokenOfferingRaised = await instanceDefault.currentTokenOfferingRaised();25 // assert.equal(currentTotalTokenOffering, 0.9e+27);26 // assert.equal(currentTokenOfferingRaised, 0);27 // });28 it("should start offering", async () => {29 let now = new Date();30 let startTime = Math.floor(now.getTime()/1000);31 let endTime = Math.floor(now.setDate(now.getDate() + 2)/1000);32 let result = await instanceDefault.startOffering(9e26, 1000, startTime, endTime, true);33 let currentTokenOfferingRaised = (await instanceDefault.currentTokenOfferingRaised()).toNumber();34 let currentTotalTokenOffering = (await instanceDefault.currentTotalTokenOffering()).toNumber();35 let offeringEnabled = await instanceDefault.offeringEnabled();36 let bonusRateOneEth = await instanceDefault.bonusRateOneEth();37 assert.equal(currentTokenOfferingRaised, 0);38 assert.equal(currentTotalTokenOffering, 9e+26);39 assert.equal(offeringEnabled, true);40 assert.equal(bonusRateOneEth, 1000);41 let sendFrom = accounts[2];42 await instanceDefault.sendTransaction({from: sendFrom, value: web3.toWei(1, "ether")});43 let balance = (await instanceDefault.balanceOf(sendFrom)).toNumber();44 assert.equal(balance, 16e+21);45 });46 it("should be received 16000 tokens when send eth to contract", async () => {47 let now = new Date();48 let startTime = Math.floor(now.getTime()/1000);49 let endTime = Math.floor(now.setDate(now.getDate() + 2)/1000);50 let result = await instanceDefault.startOffering(9e26, 1000, startTime, endTime, true);51 let sendFrom = accounts[1];52 let ownerBalanceBefore = web3.fromWei(web3.eth.getBalance(accounts[0])).toNumber();53 let senderBalanceBefore = web3.fromWei(web3.eth.getBalance(sendFrom)).toNumber();54 let gasLimit = web3.toWei(1, "Gwei"); // wei55 await instanceDefault.sendTransaction({from: sendFrom, value: web3.toWei(1, "ether"), gasLimit: gasLimit });56 let balance = (await instanceDefault.balanceOf(sendFrom)).toNumber();57 // sender should receive 16000 tokens58 assert.equal(balance, 16e+21);59 // sender balance is descreased 1 eth60 let senderBalanceAfter = web3.fromWei(web3.eth.getBalance(sendFrom)).toNumber();61 assert(senderBalanceBefore - senderBalanceAfter <= 1 + web3.fromWei(gasLimit));62 // owner should receive 1 eth63 let ownerBalanceAfter = web3.fromWei(web3.eth.getBalance(accounts[0])).toNumber();64 assert.equal(ownerBalanceBefore + 1, ownerBalanceAfter);65 });66 it("should not allow offering over offering allowance", async () => {67 await instanceDefault.endOffering();68 let now = new Date();69 let startTime = Math.floor(now.getTime()/1000);70 let endTime = Math.floor(now.setDate(now.getDate() + 2)/1000);71 let sendFrom = accounts[3];72 let result = await instanceDefault.startOffering(30000 * 1e18, 0, startTime, endTime, true)73 let balanceBefore = (await instanceDefault.balanceOf(sendFrom)).toNumber();74 75 // send ether to contract76 let success = true;77 await instanceDefault.sendTransaction({from: sendFrom, value: web3.toWei(5, "ether") })78 .then(result => success = true)79 .catch(err => success = false);80 81 let balanceAfter = (await instanceDefault.balanceOf(sendFrom)).toNumber();82 83 assert.equal(success, false);84 assert.equal(balanceBefore, balanceAfter);85 });86 it("should start offering by only owner", async () => {87 await instanceDefault.endOffering();88 let now = new Date();89 let startTime = Math.floor(now.getTime()/1000);90 let endTime = Math.floor(now.setDate(now.getDate() + 2)/1000);91 let success = true;92 let randomOfferingAmount = 30000e+18;93 await instanceDefault.startOffering(randomOfferingAmount, 0, startTime, endTime, false, {from: accounts[1]})94 .then(result => success = true)95 .catch(err => success = false);96 assert.equal(success, false); 97 });98 it("should not stop offering by accounts are not owner", async () => {99 let success = true;100 await instanceDefault.stopOffering({from: accounts[1]})101 .then(result => success = true)102 .catch(err => success = false);103 assert.equal(success, false);104 });105 it("should not resume offering by accounts are not owner", async () => {106 let result = true;107 await instanceDefault.resumeOffering({from: accounts[1]})108 .then(result => result = true)109 .catch(err => result = false);110 assert.equal(result, false);111 });112 it("should withdraw tokens by only owner", async () => {113 await instanceDefault.withdrawToken(accounts[3], 15000e+18, "0")114 .then(result => success = true)115 .catch(err => success = false);116 assert.equal(success, true); 117 let balance = (await instanceDefault.balanceOf(accounts[3])).toNumber();118 assert.equal(balance, 15000e+18);119 });120 it("should not withdraw tokens by another account", async () => {121 let success = true;122 await instanceDefault.withdrawToken(accounts[3], 15000e+18, "0", {from: accounts[1]})123 .then(result => success = true)124 .catch(err => success = false);125 assert.equal(success, false); 126 });127 it("should allow owner to set bonus rate", async () => {128 let success = true;129 let _bonusRate = 1000;130 await instanceDefault.setBonusRate(_bonusRate)131 .then(result => success = true)132 .catch(err => success = false);133 let bonusRateOneEth = (await instanceDefault.bonusRateOneEth()).toNumber();134 assert.equal(bonusRateOneEth, _bonusRate);135 assert.equal(success, true); 136 });137 it("should not allow users who are not owner to set bonus rate", async () => {138 let success = true;139 let _bonusRate = 1000;140 await instanceDefault.setBonusRate(_bonusRate, {from: accounts[1]})141 .then(result => success = true)142 .catch(err => success = false);143 assert.equal(success, false); 144 });145 // it("should be received bonus token", async () => {146 // // bonusRate = 1000147 // let sendFrom = accounts[4];148 // let gasLimit = web3.toWei(1, "Gwei"); // wei149 // let balanceSenderBefore = (await instanceDefault.balanceOf(sendFrom)).toNumber();150 // await instanceDefault.sendTransaction({from: sendFrom, value: web3.toWei(1, "ether"), gasLimit: gasLimit });151 // let balanceSenderAfter = (await instanceDefault.balanceOf(sendFrom)).toNumber();152 // assert.equal(balanceSenderAfter - balanceSenderBefore, 16000e18)153 154 // });155 it("should batchTransfer reverts when the number of receivers greater than 20", async () => {156 let receivers = accounts;157 let values = Array.from({length: receivers.length}).map((_, i) => i * 1e18);158 expect(receivers, 'number of accounts greater than 20').has.property('length').gt(20);159 expect(values).length(receivers.length);160 assertRevert(instanceDefault.batchTransfer(receivers, values));161 });162 it("should batchTransfer reverts when number of receivers differences from values", async () => {163 let receivers = accounts;164 let values = Array.from({length: 1}).map((_, i) => i * 1e18);165 expect(receivers, 'number of accounts greater than 20').has.property('length').gt(20);166 expect(values, 'the number of values difference from receivers').has.property('length').lt(receivers.length);167 assertRevert(instanceDefault.batchTransfer(receivers, values));168 });169 it("should batchTransfer reverts when total values greater than sender's balance", async () => {170 let sender = accounts[1]; 171 let senderBalance = (await instanceDefault.balanceOf(sender)).toNumber();172 expect(senderBalance, 'sender has 0 token').eq(0);173 let receivers = accounts.slice(10, 20);174 let values = Array.from({length: receivers.length}).map((_, i) => i * 1e18); 175 assertRevert(instanceDefault.batchTransfer(receivers, values, {from: sender}));176 });177 it("should batchTransfer reverts when total values overflow uint256", async () => {178 let sender = accounts[1];179 const amountSenderBalance = web3.toWei(100, 'ether');180 await instanceDefault.transfer(sender, amountSenderBalance);181 let senderBalance = (await instanceDefault.balanceOf(sender)).toString();182 expect(senderBalance).eq(amountSenderBalance);183 let receivers = accounts.slice(10, 20);184 let values = Array.from({length: receivers.length}).map( (_, i) => Math.pow(2, 255));185 186 await instanceDefault.batchTransfer(receivers, values, {from: sender})187 .then(_ => assert.fail("execution dose not throw error"))188 .catch(err => {189 expect(err.message).include('invalid opcode');190 });191 await Promise.all(receivers.map(address => instanceDefault.balanceOf(address)))192 .then(balances => {193 for (let balance of balances) {194 expect(balance.toNumber()).eq(0);195 }196 });197 });198 it("should batchTransfer reverts when balance isn't enough", async () => {199 let sender = accounts[1];200 const amountSenderBalance = web3.toWei(100, 'ether');201 await instanceDefault.transfer(sender, amountSenderBalance);202 let senderBalance = (await instanceDefault.balanceOf(sender)).toString();203 expect(senderBalance).eq(amountSenderBalance);204 let receivers = accounts.slice(10, 20);205 let values = Array.from({length: receivers.length}).map( (_, i) => web3.toWei(11, 'ether'));206 assertRevert(instanceDefault.batchTransfer(receivers, values, {from: sender}));207 });208 it("should batchTransfer success", async () => {209 let sender = owner;210 let senderBalanceBefore = (await instanceDefault.balanceOf(sender)).toNumber();211 let receivers = accounts.slice(10, 20);212 let values = Array.from({length: receivers.length}).map( (_, i) => web3.toWei(i + '', 'ether'));213 let totalToken = values.reduce((sum, n, i) => sum + i, 0); //token214 totalToken = totalToken * 1e18;215 await instanceDefault.batchTransfer(receivers, values, {from: sender});216 await Promise.all(receivers.map(address => instanceDefault.balanceOf(address)))217 .then(balances => {218 balances.forEach((balance, i) => {219 expect(balance.toString(), 'each receiver received token').eq(web3.toWei(i + '', 'ether'));220 });221 });222 let senderBalanceAfter = (await instanceDefault.balanceOf(sender)).toNumber();223 expect(senderBalanceAfter, 'sender balance must be substracted equal total value').eq(senderBalanceBefore - totalToken);224 });225});226contract.skip('TokenOffering', function (accounts) {227 it("should burn remain token when closing offering", async () => {228 let now = new Date();229 let startTime = Math.floor(now.getTime()/1000);230 let endTime = Math.floor(now.setDate(now.getDate() + 5)/1000);231 let totalOfferingTokens = 9e26;232 let currentTotalSupply = (await instanceDefault.totalSupply()).toNumber();233 await instanceDefault.startOffering(totalOfferingTokens, 1000, startTime, endTime, true);234 // check offering is started235 let isOfferingStarted = await instanceDefault.isOfferingStarted();236 assert.equal(isOfferingStarted, true)237 let isBurnInClose = await instanceDefault.isBurnInClose();238 assert.equal(isBurnInClose, true)239 // a user buys tokens240 let sendFrom = accounts[2];241 await instanceDefault.sendTransaction({from: sendFrom, value: web3.toWei(1, "ether")});242 let tokenBought = (await instanceDefault.balanceOf(sendFrom)).toNumber();243 await instanceDefault.endOffering();244 isOfferingStarted = await instanceDefault.isOfferingStarted();245 assert.equal(isOfferingStarted, false);246 // check remain tokens burned247 let totalSupplyAfter = (await instanceDefault.totalSupply()).toNumber();248 let totalSupplyShouldBe = currentTotalSupply - totalOfferingTokens + tokenBought;249 let ownerBalance = (await instanceDefault.balanceOf(accounts[0])).toNumber()250 assert.equal(new BigNumber(currentTotalSupply).sub(totalOfferingTokens), ownerBalance)251 assert.equal(totalSupplyAfter, new BigNumber(ownerBalance).plus(tokenBought));252 assert.equal(totalSupplyAfter, new BigNumber(2.1e27).plus(tokenBought));253 });254 it("should end offering", async () => {255 let now = new Date();256 let startTime = Math.floor(now.getTime()/1000);257 let endTime = Math.floor(now.getTime()/1000);258 await instanceDefault.startOffering(9e26, 1000, startTime, endTime, false);259 let sendFrom = accounts[2];260 await instanceDefault.sendTransaction({from: sendFrom, value: web3.toWei(1, "ether")});261 let balance = (await instanceDefault.balanceOf(sendFrom)).toNumber();262 assert.equal(balance, 32e+21);263 await instanceDefault.endOffering();264 let isRevert = false;265 try {266 await instanceDefault.sendTransaction({from: sendFrom, value: web3.toWei(1, "ether")})267 } catch (error) {268 isRevert = true;269 }270 assert.equal(isRevert, true);271 balance = (await instanceDefault.balanceOf(sendFrom)).toNumber();272 assert.equal(balance, 32e+21);273 let currentTotalTokenOffering = (await instanceDefault.currentTotalTokenOffering()).toNumber();274 assert.equal(currentTotalTokenOffering, 0);275 let isOfferingStarted = await instanceDefault.isOfferingStarted();276 assert.equal(isOfferingStarted, false)277 });278 it("should close current offering before start new one", async () => {279 let now = new Date();280 let startTime = Math.floor(now.getTime()/1000);281 let endTime = Math.floor(now.setDate(now.getDate() + 5)/1000);282 283 await instanceDefault.startOffering(10000e18, 1000, startTime, endTime, false);284 285 assertRevert(instanceDefault.startOffering(10000e18, 1000, startTime, endTime, false))286 });287 it("should update start timestamp", async () => {288 let now = new Date();289 let startTime = Math.floor(now.getTime()/1000);290 let endTime = Math.floor(now.setDate(now.getDate() + 5)/1000);291 // await instanceDefault.startOffering(9e26, 1000, startTime, endTime, true);292 let isOfferingStarted = await instanceDefault.isOfferingStarted();293 assert.equal(isOfferingStarted, true)294 now = new Date();295 let newStartTime = Math.floor(now.setDate(now.getDate() + 1)/1000);296 await instanceDefault.updateStartTime(newStartTime);297 let currentStartTime = await instanceDefault.startTime();298 assert.equal(newStartTime, currentStartTime);299 });300 it("should not update start timestamp over end timestamp", async () => {301 await instanceDefault.endOffering();302 let now = new Date();303 let startTime = Math.floor(now.getTime()/1000);304 let endTime = Math.floor(now.setDate(now.getDate() + 5)/1000);305 await instanceDefault.startOffering(9e26, 1000, startTime, endTime, false);306 let isOfferingStarted = await instanceDefault.isOfferingStarted();307 assert.equal(isOfferingStarted, true)308 let newStartTime = Math.floor(now.setDate(now.getDate() + 10)/1000);309 assertRevert(instanceDefault.updateStartTime(newStartTime))310 let currentStartTime = (await instanceDefault.startTime()).toNumber();311 assert.notEqual(newStartTime, currentStartTime);312 assert.equal(startTime, currentStartTime);313 });314 it("should not update start timestamp in closed offering", async () => {315 await instanceDefault.endOffering();316 let isOfferingStarted = await instanceDefault.isOfferingStarted();317 assert.equal(isOfferingStarted, false)318 let now = new Date();319 let newStartTime = Math.floor(now.setDate(now.getDate() + 10)/1000);320 assertRevert(instanceDefault.updateStartTime(newStartTime)) 321 });322 it("should update end timestamp", async () => {323 let now = new Date();324 let startTime = Math.floor(now.getTime()/1000);325 let endTime = Math.floor(now.setDate(now.getDate() + 5)/1000);326 await instanceDefault.startOffering(9e26, 1000, startTime, endTime, false);327 328 let isOfferingStarted = await instanceDefault.isOfferingStarted();329 assert.equal(isOfferingStarted, true)330 331 now = new Date();332 let newEndTime = Math.floor(now.setDate(now.getDate() + 4)/1000);333 await instanceDefault.updateEndTime(newEndTime);334 let currentEndTime = await instanceDefault.endTime();335 assert.equal(newEndTime, currentEndTime);336 newEndTime = Math.floor(now.setDate(now.getDate() + 6)/1000);337 await instanceDefault.updateEndTime(newEndTime);338 currentEndTime = await instanceDefault.endTime();339 assert.equal(newEndTime, currentEndTime);340 341 });342 it("should not update end timestamp less than start times", async () => {343 let isOfferingStarted = await instanceDefault.isOfferingStarted();344 assert.equal(isOfferingStarted, true)345 let now = new Date();346 let newEndTime = Math.floor(now.setDate(now.getDate() - 10)/1000);347 assertRevert(instanceDefault.updateStartTime(newEndTime)) 348 });349 it("should not update end timestamp in closed offering", async () => {350 await instanceDefault.endOffering();351 let isOfferingStarted = await instanceDefault.isOfferingStarted();352 assert.equal(isOfferingStarted, false)353 let now = new Date();354 let newEndTime = Math.floor(now.setDate(now.getDate() + 10)/1000);355 assertRevert(instanceDefault.updateStartTime(newEndTime)) 356 });357 it("should not update burnable token", async () => {358 let isOfferingStarted = await instanceDefault.isOfferingStarted();359 assert.equal(isOfferingStarted, false)360 assertRevert(instanceDefault.updateBurnableStatus(true)) 361 });362 it("should update burnable token", async () => {363 let now = new Date();364 let startTime = Math.floor(now.getTime()/1000);365 let endTime = Math.floor(now.setDate(now.getDate() + 5)/1000);366 await instanceDefault.startOffering(9e26, 1000, startTime, endTime, true);367 let isOfferingStarted = await instanceDefault.isOfferingStarted();368 assert.equal(isOfferingStarted, true)369 let currentBurnableStatus = await instanceDefault.isBurnInClose();370 assert.equal(currentBurnableStatus, true)371 await instanceDefault.updateBurnableStatus(false);372 assert.equal( await instanceDefault.isBurnInClose(), false )373 374 }); 375});376contract('ContractSpendToken', function (accounts) {377 const owner = accounts[0];378 const spendContract = accounts[3];379 beforeEach(async function () {380 instanceDefault = await ContractiumToken.deployed();381 });382 it('should add trusted contract address success', async function() {383 await instanceDefault.addContract(spendContract, accounts[1]);384 let receiver = await instanceDefault.getContractReceiver(spendContract);385 expect(receiver).eq(accounts[1]);386 });387 it('should add trusted contract address failed', async function() {388 let rsMissingContract = instanceDefault.addContract('', accounts[1]);389 assertRevert(rsMissingContract);390 let rsMissingAccount = instanceDefault.addContract(spendContract, '');391 assertRevert(rsMissingAccount);392 let rsMissingAll = instanceDefault.addContract();393 assertRevert(rsMissingAll);394 });395 396 it('should remove contract success', async function() {397 await instanceDefault.addContract(spendContract, accounts[1]);398 await instanceDefault.removeContract(spendContract); 399 let receiver = await instanceDefault.getContractReceiver(spendContract);400 expect(receiver, 'remove success').eq('0x0000000000000000000000000000000000000000'); 401 });402 it('should spend token', async function() {403 404 const initBalance = web3.toWei(1000, 'ether');405 const spendToken = web3.toWei(10, 'ether');406 await instanceDefault.transfer(accounts[2], initBalance);407 await instanceDefault.addContract(spendContract, accounts[1]);408 await instanceDefault.contractSpend(accounts[2], spendToken, {from: spendContract});409 const balance = (await instanceDefault.balanceOf(accounts[2])).toNumber();410 expect(balance).eq(initBalance - spendToken);411 const receiverBalance = (await instanceDefault.balanceOf(accounts[1])).toNumber();412 expect(receiverBalance + '').eq(spendToken);413 });414 it('should spend token failed', async function() {415 const spendToken = web3.toWei(10, 'ether');416 assertRevert(instanceDefault.contractSpend(accounts[2], spendToken));417 });418 it('should only owner can get receiver address from contract address', async function() {419 await instanceDefault.addContract(spendContract, accounts[1]);420 assertRevert(instanceDefault.getContractReceiver(spendContract, {from: accounts[1]}));421 const addr = await instanceDefault.getContractReceiver(spendContract, {from: owner});422 expect(addr).eq(accounts[1]);423 });424});425const assertRevert = async promise => {426 try {427 await promise;428 assert.fail('Expected revert not received');429 } catch (error) {430 const revertFound = error.message.search('revert') >= 0;431 assert(revertFound, `Expected "revert", got ${error} instead`);432 }...
Api.js
Source:Api.js
1// Configs2const VALID_HTTP_METHODS = ['GET','POST','PUT','DELETE']3const LANG = require('./lang.json')45// Modules6const QueryString = require('query-string')7const merge = require('deepmerge')8const axios = require('axios')910/**11 * @class ApiRequestBuilder12 * 13 * @todo namespaces14 * @todo cancel requests15 * @todo replace/abort request by namespace16 * @todo default callbacks/actions by status code17 */18class ApiRequestBuilder {19 constructor(params = {}){20 // Configurations21 this.validMethods = params.validMethods || VALID_HTTP_METHODS22 this.lang = {...LANG, ...params.lang || {}}23 this.tokenAsParam = params.tokenAsParam24 this.translateErrors = typeof params.translateErrors == "undefined" ? true : params.translateErrors2526 // Defaults27 this.server = params.server || 'http://localhost'28 29 this.endpoint = params.endpoint30 this.path = params.path31 this.vars = params.vars // Path variables32 this.params = params.params33 this.mime = params.mime || "application/json"34 this.headers = params.headers || {}3536 this.token = params.token3738 this.timeout = params.timeout || 500003940 // Requests stack41 this.requests = {}42 }43 /**44 * Build url45 * 46 * @todo Sanitize vars47 * 48 * @param {object} buildParams49 * @param {string|InstanceDefault|'http://localhost'} buildParams.server API Server url with protocol 50 * @param {string|InstanceDefault|''} buildParams.endpoint API Endpoint 51 * @param {string|InstanceDefault|''} buildParams.path Request path52 * @param {object|{}} buildParams.vars Path variables53 * @param {object|{}} buildParams.params Request query parameters54 * @param {string|InstanceDefault|undefined} buildParams.token Request auth token55 * @param {string|InstanceDefault|false} buildParams.tokenAsParam Auth token name as param56 * 57 * @returns {string} Full request URL58 */59 buildURL(buildParams = {}){60 const {61 server = this.server,62 endpoint = this.endpoint,63 token = this.token,64 tokenAsParam = this.tokenAsParam,65 } = buildParams66 let { path = this.path, vars = {}, params = {} } = buildParams6768 // Base URL69 let url = `${server}${endpoint ? `/${endpoint}` : ''}`70 // Path71 if(path) {72 // Merge vars if has default73 vars = (typeof this.vars == "object") ? merge(this.vars, vars) : vars74 // Replace path vars75 Object.keys(vars).map( key => {76 path = path.replace(`{${key}}`, vars[key])77 })78 // Append path to url79 url += `/${path}`80 }81 // Merge params if has default82 params = (typeof this.params == "object") ? merge(this.params, params) : params83 // Token as param?84 if(tokenAsParam) params[tokenAsParam] = token85 // Stringify params and append to url if has elements86 if(Object.keys(params).length) url += `?${QueryString.stringify( params )}`87 // All done!88 return url89 }90 get(data = {}){91 data.method = 'GET'92 return this.httpRequest(data)93 }94 post(data = {}){95 data.method = 'POST'96 return this.httpRequest(data)97 }98 put(data = {}){99 data.method = 'PUT'100 return this.httpRequest(data)101 }102 delete(data = {}){103 data.method = 'DELETE'104 return this.httpRequest(data)105 }106 /**107 * 108 * @param {object} requestData 109 * 110 * @param {string|'GET'} requestData.method111 * 112 * @param {string|InstanceDefault|'http://localhost'} requestData.server API Server url with protocol 113 * @param {string|InstanceDefault|''} requestData.endpoint API Endpoint 114 * @param {string|InstanceDefault|''} requestData.path Request path115 * @param {object|{}} requestData.vars Path variables116 * @param {object|{}} requestData.params Request query parameters117 * 118 * @param {string|InstanceDefault|'application/json'} requestData.mime Request mime (content-type)119 * @param {object|{}} requestData.headers Request headers120 * 121 * @param {string|InstanceDefault|undefined} requestData.auth Request auth token122 * @param {string|InstanceDefault|false} requestData.tokenAsParam Auth token name as param123 */124 httpRequest(requestData = {}){125 // Consts that MUST exist in spread126 const {tokenAsParam = this.tokenAsParam } = requestData127 // Consts spread128 const {129 // URL Params130 server, endpoint, path = '', vars, params,131 // Auth params132 auth = this.token && !tokenAsParam ? this.token : undefined,133 // Header params134 mime = this.mime,135 // Config params136 lang , translateErrors = this.translateErrors, timeout = this.timeout } = requestData137 // Variables spread138 let { method = 'GET', data = {}, headers = {} } = requestData139140 // Promise141 return new Promise((resolve, reject) => {142 let url143 // Create URL144 try {145 url = this.buildURL({146 server,147 endpoint,148 path,149 vars,150 params,151 token: tokenAsParam ? token : undefined,152 tokenAsParam153 })154 } catch (err) {155 // Error building URL156 return reject(err)157 }158 // Validate method159 method = method.toUpperCase()160 if(!this.validMethods.includes(method)) return reject( "METHOD_NOT_ALLOWED" )161 // Remove data in GET && DELETE methods162 if(method == "GET" || method == "DELETE"){163 data = undefined164 }165166 // Merge headers if has default167 headers = (typeof this.headers == "object") ? merge(this.headers, headers) : headers168169 // Set headers170 if(auth) headers['Authorization'] = 'Bearer ' + auth171172 // HTTP Query173 axios({174 url,175 method,176 data,177 contentType: (typeof data == 'object') ? `${mime}; charset=utf-8` : undefined,178 dataType: 'json',179 json: true,180 headers,181 timeout: timeout,182 cache : (method == "GET") ? false : undefined,183 })184 .then(res => resolve(res.data))185 .catch(err => reject(translateErrors ? this.stringifyError(err.response, lang) : err))186 })187 }188189 stringifyError(err = {}, lang = this.lang){190 // Spread191 let { status = 500, statusText, data } = err192193 // Custom cases194 switch(status){195 case 0:196 switch(statusText){197 case 'timeout':198 status = "TIMEOUT"199 statusText = "Connection timed out"200 break201 case 'error':202 status = "ERROR"203 statusText = "Connection error"204 break205 }206 break207 }208 // Return - langed status code || Default status text || Raw data209 return lang[statusText] || lang[status] || statusText || data210 }211}212213// Exports214module.exports = params => new ApiRequestBuilder(params)215module.exports.Class = ApiRequestBuilder216217module.exports.VALID_HTTP_METHODS218module.exports.LANG219220// JSDocs221222/**223 * Default value defined in the constructor224 * @typedef {*} InstanceDefault
...
httpApi.js
Source:httpApi.js
1import axios from 'axios';2import { parseResponse } from '../utils/Utils';3import * as ROUTES from '../constants/endpoints';4//TODO: Be aware where the port is going to be5const instanceDefault = axios.create({ baseURL: 'http://' + ROUTES.SERVER_HOST + ':' + ROUTES.SERVER_PORT }); // this is for firebase6/**7 * This File is for parsing and anything processing middleware with diferent directions8 */9export default {10 user: {11 login: credentials => instanceDefault.post(ROUTES.LOGIN_ENDPOINT, { credentials })12 .then((res) => {13 console.log('Response in Api Login:');14 let result = parseResponse(res);15 console.log(result);16 return result;17 }),18 signup: params => instanceDefault.post(ROUTES.CREATE_USER_ENDPOINT, { params })19 .then((res) => {20 console.log('Response in Api Signup');21 let result = parseResponse(res);22 console.log(result);23 return result;24 })25 },26 mediaLenguaVocabulary: {27 translate_kichwa_spanish: word_kichwa => instanceDefault.post(ROUTES.TRANSLATE_KICHWA_SPANISH_MEDIA_LENGUA_ENDPOINT, { word_kichwa })28 .then(res => {29 console.log('Response in Api Translate');30 res.data31 }),32 getValueByQuery: input => {33 return instanceDefault.post(ROUTES.GET_OBJECT_BY_QUERY_ENDPOINT, { input });34 }35 },36 kichwaVocabulary:{37 getKichwaWords: () => {38 return instanceDefault.get(ROUTES.GET_KICHWA_WORDS_ENDPOINT, null);39 }40 },41 files: {42 uploadFiles: input => {43 let headersFiles = { 'Content-Type': 'multipart/form-data' }44 return instanceDefault.post(ROUTES.UPLOAD_FILES_ENDPOINT, input, { headers: headersFiles })45 }46 }...
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!!