Best JavaScript code snippet using mountebank
strnum.js
Source:strnum.js
1const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;2const numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;3// const octRegex = /0x[a-z0-9]+/;4// const binRegex = /0x[a-z0-9]+/;5//polyfill6if (!Number.parseInt && window.parseInt) {7 Number.parseInt = window.parseInt;8}9if (!Number.parseFloat && window.parseFloat) {10 Number.parseFloat = window.parseFloat;11}12 13const consider = {14 hex : true,15 leadingZeros: true,16 decimalPoint: "\.",17 eNotation: true18 //skipLike: /regex/19};20function toNumber(str, options = {}){21 // const options = Object.assign({}, consider);22 // if(opt.leadingZeros === false){23 // options.leadingZeros = false;24 // }else if(opt.hex === false){25 // options.hex = false;26 // }27 options = Object.assign({}, consider, options );28 if(!str || typeof str !== "string" ) return str;29 30 let trimmedStr = str.trim();31 // if(trimmedStr === "0.0") return 0;32 // else if(trimmedStr === "+0.0") return 0;33 // else if(trimmedStr === "-0.0") return -0;34 if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;35 else if (options.hex && hexRegex.test(trimmedStr)) {36 return Number.parseInt(trimmedStr, 16);37 // } else if (options.parseOct && octRegex.test(str)) {38 // return Number.parseInt(val, 8);39 // }else if (options.parseBin && binRegex.test(str)) {40 // return Number.parseInt(val, 2);41 }else{42 //separate negative sign, leading zeros, and rest number43 const match = numRegex.exec(trimmedStr);44 if(match){45 const sign = match[1];46 const leadingZeros = match[2];47 let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros48 //trim ending zeros for floating number49 50 const eNotation = match[4] || match[6];51 if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-012352 else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //012353 else{//no leading zeros or leading zeros are allowed54 const num = Number(trimmedStr);55 const numStr = "" + num;56 if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation57 if(options.eNotation) return num;58 else return str;59 }else if(eNotation){ //given number has enotation60 if(options.eNotation) return num;61 else return str;62 }else if(trimmedStr.indexOf(".") !== -1){ //floating number63 // const decimalPart = match[5].substr(1);64 // const intPart = trimmedStr.substr(0,trimmedStr.indexOf("."));65 66 // const p = numStr.indexOf(".");67 // const givenIntPart = numStr.substr(0,p);68 // const givenDecPart = numStr.substr(p+1);69 if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.070 else if(numStr === numTrimmedByZeros) return num; //0.456. 0.7900071 else if( sign && numStr === "-"+numTrimmedByZeros) return num;72 else return str;73 }74 75 if(leadingZeros){76 // if(numTrimmedByZeros === numStr){77 // if(options.leadingZeros) return num;78 // else return str;79 // }else return str;80 if(numTrimmedByZeros === numStr) return num;81 else if(sign+numTrimmedByZeros === numStr) return num;82 else return str;83 }84 if(trimmedStr === numStr) return num;85 else if(trimmedStr === sign+numStr) return num;86 // else{87 // //number with +/- sign88 // trimmedStr.test(/[-+][0-9]);89 // }90 return str;91 }92 // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str;93 94 }else{ //non-numeric string95 return str;96 }97 }98}99/**100 * 101 * @param {string} numStr without leading zeros102 * @returns 103 */104function trimZeros(numStr){105 if(numStr && numStr.indexOf(".") !== -1){//float106 numStr = numStr.replace(/0+$/, ""); //remove ending zeros107 if(numStr === ".") numStr = "0";108 else if(numStr[0] === ".") numStr = "0"+numStr;109 else if(numStr[numStr.length-1] === ".") numStr = numStr.substr(0,numStr.length-1);110 return numStr;111 }112 return numStr;113}...
check_input.js
Source:check_input.js
1function validateEmail(email) {2 /*3 validate email against allowed list4 https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript5 */6 const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;7 return re.test(String(email).toLowerCase());8}9function is_form_input_valid(form){10 /*11 check input from form 12 */13 if(form==null || form.elements["contactname"]==null || form.elements["email"]==null || form.elements["subject"] == null || 14 form.elements["content"] == null){15 return [false,null,"ElemIsNull"];16 }17 var input_list=form.getElementsByTagName("input");18 for(let cur_input_elem of input_list){19 var cur_input=cur_input_elem.value;20 21 if(cur_input_elem.id=="encryptedmessage"){22 continue; 23 } 24 if(cur_input.length<2){ 25 return [false,cur_input_elem, "TooSmall"];26 }27 if(cur_input_elem.id=="email" && !validateEmail(cur_input)){ 28 return [false, cur_input_elem,"InvalidMail"]; 29 } 30 }; 31 return [true,"OK"];32 33}34function escapeHtml(unsafe) {35 /*36 escape input from server 37 https://stackoverflow.com/questions/6234773/can-i-escape-html-special-chars-in-javascript/1810846338 */39 return unsafe40 .replace(/&/g, "&")41 .replace(/</g, "<")42 .replace(/>/g, ">")43 .replace(/"/g, """)44 .replace(/'/g, "'");45}46function trim_pgp_message(encrypted){47 /*48 trimm input that only base64 characters from the actual pgp ciphertext will be transmitted to the backend.49 allow list check doesn't need to take care about difficult pgp comment stuff 50 --> more restrictive = more secure51 */52 var trimmed=encrypted;53 trimmed=trimmed.replace("-----BEGIN PGP MESSAGE-----","");54 trimmed=trimmed.replace("-----END PGP MESSAGE-----","");55 trimmed=trimmed.replace("Version:","");56 trimmed=trimmed.replace("OpenPGP.js","");57 trimmed=trimmed.replace("Comment:","");58 trimmed=trimmed.replace("https://openpgpjs.org","");59 trimmed=trimmed.replace(/(v\d\.[\d|\.]+)/gi,"");60 trimmed=trimmed.trim();61 return trimmed;...
trimNonCicularRangeByAnotherNonCircularRange.ts
Source:trimNonCicularRangeByAnotherNonCircularRange.ts
1import { AnnRange } from "./types";2// var ac = require('ve-api-check'); 3export function trimNonCicularRangeByAnotherNonCircularRange(rangeToBeTrimmed: AnnRange, trimmingRange: AnnRange) {4 // ac.throw([ac.range, ac.range], arguments);5 let outputTrimmedRange;6 if (!rangeToBeTrimmed) {7 return rangeToBeTrimmed;8 }9 if (rangeToBeTrimmed.start < trimmingRange.start) {10 if (rangeToBeTrimmed.end < trimmingRange.start) {11 // rrr <range to be trimmed12 // ttt <trimming range13 outputTrimmedRange = {14 start: rangeToBeTrimmed.start,15 end: rangeToBeTrimmed.end16 };17 } else {18 if (rangeToBeTrimmed.end > trimmingRange.end) {19 // rrrrrr <range to be trimmed20 // ttt <trimming range21 outputTrimmedRange = {22 start: rangeToBeTrimmed.start,23 end: rangeToBeTrimmed.end24 };25 } else {26 // rrrrrr <range to be trimmed27 // ttt <trimming range28 outputTrimmedRange = {29 start: rangeToBeTrimmed.start,30 end: trimmingRange.start - 131 };32 }33 }34 } else {35 if (rangeToBeTrimmed.end <= trimmingRange.end) {36 // rrr <range to be trimmed37 // ttttt <trimming range38 //fully deleting the range, so do nothing39 } else {40 if (rangeToBeTrimmed.start > trimmingRange.end) {41 // rrrrrr <range to be trimmed42 // ttt <trimming range43 outputTrimmedRange = {44 end: rangeToBeTrimmed.end,45 start: rangeToBeTrimmed.start46 };47 } else {48 // rrrrrr <range to be trimmed49 // ttt <trimming range50 outputTrimmedRange = {51 end: rangeToBeTrimmed.end,52 start: trimmingRange.end + 153 };54 }55 }56 }57 return outputTrimmedRange;...
Using AI Code Generation
1const mb = require('mountebank');2mb.start({3}).then(function () {4 console.log('Mountebank started');5});6const mb = require('mountebank');7mb.start({8}).then(function () {9 console.log('Mountebank started');10});11const mb = require('mountebank');12mb.start({13}).then(function () {14 console.log('Mountebank started');15});16const mb = require('mountebank');17mb.start({18}).then(function () {19 console.log('Mountebank started');20});21const mb = require('mountebank');22mb.start({23}).then(function () {24 console.log('Mountebank started');25});26const mb = require('mountebank');27mb.start({28}).then(function () {29 console.log('Mountebank started');30});31const mb = require('mountebank');32mb.start({
Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3 {4 {5 is: {6 headers: {7 },8 body: {9 }10 }11 }12 }13};14mb.create({port: 2525, pidfile: 'mb.pid'}, function (error, mbServer) {15 mbServer.post('/imposters', imposter, function (error, response) {16 console.log('imposter created');17 });18});19mbServer.get('/imposters/4545', function (error, response) {20 console.log('imposter retrieved');21 console.log(response.body);22});23mbServer.del('/imposters/4545', function (error, response) {24 console.log('imposter deleted');25});26mbServer.del('/imposters', function (error, response) {27 console.log('all imposters deleted');28});29mbServer.get('/logs', function (error, response) {30 console.log('logs retrieved');31 console.log(response.body);32});33mbServer.del('/logs', function (error, response) {34 console.log('logs deleted');35});36mbServer.get('/config', function (error, response) {37 console.log('config retrieved');38 console.log(response.body);39});40mbServer.put('/config', { port: 4545 }, function (error, response) {41 console.log('config updated');42 console.log(response.body);43});44mbServer.del('/config', function (error, response) {45 console.log('config deleted');46});47mbServer.get('/imposters', function (error, response) {48 console.log('all imposters retrieved');49 console.log(response.body);50});51mbServer.get('/imposters/4545/requests', function (error, response) {52 console.log('requests retrieved');53 console.log(response.body);54});55mbServer.del('/imposters/4545/requests', function (error, response) {56 console.log('requests deleted');57});58mbServer.del('/imposters/4545/stubs/1', function (error, response) {59 console.log('stub deleted');60});61mbServer.put('/imposters/4545/stubs/1',
Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create({3 {4 {5 is: {6 headers: {7 },8 body: JSON.stringify({message: 'Hello World'})9 }10 }11 }12});13imposter.then(function (imposter) {14 console.log('Imposter created on port %s', imposter.port);15}).done();16var mb = require('mountebank');17var imposter = mb.create({18 {19 {20 is: {21 headers: {22 },23 body: JSON.stringify({message: 'Hello World'})24 }25 }26 }27});28imposter.then(function (imposter) {29 console.log('Imposter created on port %s', imposter.port);30}).done();31var mb = require('mountebank');32var imposter = mb.create({33 {34 {35 is: {36 headers: {37 },38 body: JSON.stringify({message: 'Hello World'})39 }40 }41 }42});43imposter.then(function (imposter) {44 console.log('Imposter created on port %s', imposter.port);45}).done();46var mb = require('mountebank');47var imposter = mb.create({48 {49 {50 is: {51 headers: {52 },53 body: JSON.stringify({message: 'Hello World'})54 }55 }56 }57});
Using AI Code Generation
1var mb = require('mountebank');2var assert = require('assert');3 {4 {5 {6 is: {7 headers: {8 },9 }10 }11 }12 }13];14mb.start({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*']}, function () {15 mb.createImposters(2525, imposters, function () {16 mb.get('/', 3000, function (response) {17 assert.equal(response.body, 'Hello World!');18 mb.stop(2525, function () {19 console.log('All done');20 });21 });22 });23});
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var protocol = 'http';4var stub = {5 {6 is: {7 }8 }9};10var mb = require('mountebank');11var port = 2525;12var protocol = 'http';13var stub = {14 {15 is: {16 }17 }18};19var promise = mb.start({20});21promise.then(function () {22 return mb.post('/imposters', {23 });24}).then(function (response) {25 console.log(response.body);26 return mb.del('/imposters/' + response.body.port);27}).then(function () {28 return mb.stop();29}).catch(function (error) {30 console.error(error);31});32{ port: 2525, protocol: 'http', numberOfRequests: 0 }
Using AI Code Generation
1var mb = require('mountebank');2mb.create({port:2525, pidfile:'mb.pid', logfile:'mb.log', ipWhitelist: ['*']}, function (error, imposter) {3 if (error) {4 console.error('Failed to create imposter: ' + error.message);5 }6 else {7 console.log('Created imposter with PID: ' + imposter.pid);8 }9});
Using AI Code Generation
1var mb = require('mountebank');2var path = require('path');3var fs = require('fs');4var Q = require('q');5var mbPort = 2525;6var mbHost = 'localhost';7var mbProtocol = 'http';8var mbConfig = {9};10var mbOptions = {11 cwd: path.resolve(__dirname, 'mb'),12};13function startMb() {14 var deferred = Q.defer();15 mb.create(mbConfig, mbOptions, function (error, imposter) {16 if (error) {17 console.error('Error creating mountebank', error);18 deferred.reject(error);19 } else {20 console.log('Mountebank started');21 deferred.resolve(imposter);22 }23 });24 return deferred.promise;25}26function createImposter(imposter) {27 var deferred = Q.defer();28 imposter.create({ port: 6000, protocol: 'http' }, function (error, imposter) {29 if (error) {30 console.error('Error creating imposter', error);31 deferred.reject(error);32 } else {33 console.log('Imposter created');34 deferred.resolve(imposter);35 }36 });37 return deferred.promise;38}39function createStub(imposter) {40 var deferred = Q.defer();41 imposter.addStub({42 {43 equals: {44 }45 }46 {47 is: {48 headers: { 'Content-Type': 'application/json' },49 body: JSON.stringify({ message: 'Hello World!' })50 }51 }52 }, function (error, imposter) {53 if (error) {54 console.error('Error creating stub', error);55 deferred.reject(error);56 } else {57 console.log('Stub created');58 deferred.resolve(imposter);59 }60 });61 return deferred.promise;62}63function getResponse(imposter) {64 var deferred = Q.defer();65 var request = require('request');66 request(mbUrl + '/imposters
Using AI Code Generation
1var mb = require('mountebank');2var fs = require('fs');3var path = require('path');4var api = require('q-io/http');5var Q = require('q');6var port = 2525;7var imposterPort = 3000;8var stubs = JSON.parse(fs.readFileSync(path.join(__dirname, 'stubs.json'), 'utf8'));9var imposter = { port: imposterPort, protocol: 'http', stubs: stubs };10var options = { url: imposterUrl + '/test', method: 'GET' };11var logger = mb.createLogger({ mode: 'test' });12var server = mb.create({ port: port, logger: logger });13server.start()14 .then(function () {15 return server.addStub(imposter);16 })17 .then(function () {18 return api.request(options);19 })20 .then(function (response) {21 console.log(response.body);22 return server.stop();23 })24 .done();25 {26 {27 "equals": {28 }29 }30 {31 "is": {32 }33 }34 }35var mb = require('mountebank');36var fs = require('fs');37var path = require('path');38var api = require('q-io/http');39var Q = require('q');40var port = 2525;41var imposterPort = 3000;42var stubs = JSON.parse(fs.readFileSync(path.join(__dirname, 'stubs.json'), 'utf8'));43var imposter = { port: imposterPort, protocol: 'http', stubs: stubs };
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!!