Best JavaScript code snippet using mountebank
types.js
Source:types.js
1"use strict";2require("../lib/bootstrap.js");3var types = require("../lib/types.js");4describe ("bundled types", function () {5 describe("check function", function () {6 it("pass", function () {7 var goodArgs, badArgs, nextArgs, checkFn;8 goodArgs = {9 "Object": [10 {},11 [],12 Object.create(Object.prototype)13 ],14 "Array": [15 [],16 new Array,17 Array(10)18 ],19 "Function": [20 Function,21 function () {},22 Object23 ],24 "RegExp": [25 /blah/,26 new RegExp,27 RegExp(),28 Object.create(RegExp.prototype)29 ],30 "Date": [31 new Date,32 Object.create(Date.prototype)33 ],34 "Symbol": [35 Symbol()36 ],37 "String": [38 new String(),39 Object.create(String.prototype)40 ],41 "Number": [42 new Number(),43 Object.create(Object.getPrototypeOf(4))44 ],45 "Boolean": [46 new Boolean(),47 Object.create(Boolean.prototype)48 ],49 "null": [50 null51 ],52 "undefined": [53 undefined,54 root.undefined55 ],56 "string": [57 "blah",58 "",59 String(),60 String(144)61 ],62 "number": [63 18,64 18.8,65 Infinity66 ],67 "integer": [68 18,69 -1870 ],71 "float": [72 18.5,73 -18.5,74 Infinity,75 -Infinity76 ],77 "boolean": [78 true,79 false,80 true,81 Boolean(0),82 Boolean(""),83 Boolean(new Boolean)84 ],85 "NaN": [86 NaN,87 NaN + 188 ]89 };90 badArgs = {91 "Object": [92 Object.create(null),93 null94 ],95 "Array": [96 {},97 null,98 undefined,99 Object.create(Array.prototype)100 ],101 "Function": [102 {},103 [],104 Object.create(Function.prototype),105 Function.prototype106 ],107 "RegExp": [108 {},109 []110 ],111 "Date": [112 [],113 {},114 Date()// -> string format115 ],116 "String": [117 String(),118 ""119 ],120 "Number": [121 Number(),122 4,123 4.4,124 Infinity,125 -Infinity,126 NaN127 ],128 "Boolean": [129 true,130 false,131 Boolean(0),132 Boolean("true")133 ],134 "null": [135 {},136 undefined,137 "",138 0139 ],140 "undefined": [141 null,142 0,143 "",144 false145 ],146 "string": [147 new String,148 Object.create(Object.getPrototypeOf(""))149 ],150 "number": [151 new Number,152 Object.create(Number.prototype),153 NaN154 ],155 "integer": [156 3.3,157 NaN,158 Infinity159 ],160 "float": [161 3,162 NaN163 ],164 "boolean": [165 new Boolean(0),166 Infinity,167 0,168 NaN,169 ""170 ],171 "NaN": [172 true,173 false,174 1175 ]176 };177 // keeping it DRY178 for (var type in types) {179 if (!types.hasOwnProperty(type)) continue;180 checkFn = types[type][1];181 nextArgs = goodArgs[type];182 if (!nextArgs) throw new Error("missing test for " + type);183 for (var arg in nextArgs) {184 if (!nextArgs.hasOwnProperty(arg)) continue;185 logStderr("checkFn", true, type, checkFn, nextArgs[arg]);186 expect(checkFn(nextArgs[arg])).toBe(true);187 }188 nextArgs = badArgs[type];189 for (var arg in nextArgs) {190 if (!nextArgs) throw new Error("missing test for " + type);191 if (!nextArgs.hasOwnProperty(arg)) continue;192 logStderr("checkFn", false, type, checkFn, nextArgs[arg]);193 expect(checkFn(nextArgs[arg])).toBe(false);194 }195 }196 });197 });198 describe("regex functions", function () {199 it ("work approprately", function () {200 var goodStrs = {201 "Object": [202 "Object", "object", "Obj", "obj", "!object", "!!object", "no wrong obj",203 "no,wront,obj", "no|wrong|obj", "no|wrong stil-bad,obj",204 "no| ,wrong| ,obj", "no|||wront still-wrong,,,obj", "one,two,obj,"205 ],206 "Array": ["Array", "array", "Arr", "arr"],207 "Function": ["Function", "function", "Func", "func", "Fn", "fn"],208 "RegExp": ["RegExp", "regExp", "regexp", "regExp"],209 "Date": ["Date", "date"],210 "Symbol": ["Symbol", "symbol", "Sym", "sym"],211 "String": ["String", "Str"],212 "Number": ["Number", "Num"],213 "Boolean": ["Boolean", "Bool"],214 "null": ["null"],215 "undefined": ["undefined"],216 "string": ["string", "str"],217 "number": ["number", "num"],218 "integer": ["integer", "int"],219 "float": ["float", "flt"],220 "boolean": ["bool", "boolean"],221 "NaN": ["NaN", "Nan", "naN", "nan"]222 };223 var badStrs = {224 "Object": [225 "", "o", "one-two-obj", "onetwoobj", "one_obj_two"226 ],227 "NaN": ["nAn"]228 };229 var strs, str, reFn;230 // keeping it DRY231 for (var type in types) {232 if (!types.hasOwnProperty(type)) continue;233 reFn = types[type][0];234 strs = goodStrs[type];235 for (var ind in strs) {236 if (!strs) throw new Error("missing test for " + type);237 if (!strs.hasOwnProperty(ind)) continue;238 str = strs[ind];239 logStderr("reFn", true, "<void>", reFn, str);240 expect(reFn(str)).not.toBe(null);241 }242 strs = badStrs[type];243 for (var ind in strs) {244 if (!strs) throw new Error("missing test for " + type);245 if (!strs.hasOwnProperty(ind)) continue;246 str = strs[ind];247 logStderr("reFn", false, "<void>", reFn, str);248 expect(reFn(str)).toBe(null);249 }250 }251 });252 });253 function logStderr (section, goodArg, expType, checkFn, subj) {254 var util = require("util");255 var com = ",",256 crlf = "\r\n",257 sp = "\u0020",258 arrow = "->",259 subjString,260 subjTypeof = typeof subj,261 checkFnRet = checkFn(subj);262 // prepare for Error: toString() is not generic263 // e.g. when Object.create(Function.prototype).toString()264 try {265 subjString = null != subj && subj.toString !== undefined ?266 subj.toString() :267 util.inspect(subj, {depth: 1, colors: false});268 } catch (e) {269 subjString = "";270 }271 console.error (272 section + crlf +273 (goodArg ? "good" : "bad") + crlf +274 "type" + sp + arrow + sp + expType + crlf +275 "fn" + sp + arrow + sp + (checkFn.name || checkFn._name) + crlf +276 "subj as string" + sp + arrow + sp + subjString + crlf +277 "typeof subj" + sp + arrow + sp + typeof subj + crlf +278 "fn result" + sp + arrow + sp + checkFn(subj) + crlf279 + crlf280 );281 }...
throttle.ts
Source:throttle.ts
1import {setTimeout} from 'timers'2export class CanceledError extends Error {3 constructor() {4 super('throttled invocation was canceled')5 this.name = 'CanceledError'6 }7}8class Delay {9 ready: Promise<void>10 effect: Promise<void> | void11 timeout!: NodeJS.Timeout12 constructor(lastInvocationDone: Promise<any>, wait: number) {13 this.effect = new Promise(resolve => {14 this.timeout = setTimeout(resolve, wait)15 })16 this.ready = lastInvocationDone.then(() => this.effect)17 }18 flush() {19 clearTimeout(this.timeout)20 this.effect = undefined21 }22 cancel() {23 clearTimeout(this.timeout)24 this.effect = Promise.reject(new CanceledError())25 this.effect.catch(() => {26 // stuff27 })28 }29}30export function throttle(31 fn: (...args: any) => Promise<any>,32 _wait: number,33 options: {34 getNextArgs?: (args0: any, args1: any) => any;35 } = {}36): {37 (...args: any): Promise<any>;38 cancel: () => Promise<void>;39 flush: () => Promise<void>;40 } {41 const wait = _wait !== null && Number.isFinite(_wait) ? Math.max(_wait, 0) : 042 const getNextArgs = options.getNextArgs || ((prev, next) => next)43 let nextArgs: any44 let lastInvocationDone: Promise<any> = Promise.resolve()45 let delay: Delay = new Delay(lastInvocationDone, 0)46 let nextInvocation: Promise<any> | null = null47 function invoke(): Promise<any> {48 const args = nextArgs49 if (!args) throw new Error('unexpected error: nextArgs is null')50 nextInvocation = null51 nextArgs = null52 const result = fn(...args)53 lastInvocationDone = result.catch(() => {54 // ignore55 })56 delay = new Delay(lastInvocationDone, wait)57 return result58 }59 function wrapper(...args: any): Promise<any> {60 nextArgs = nextArgs ? getNextArgs(nextArgs, args) : args61 if (!nextArgs) throw new Error('unexpected error: nextArgs is null')62 if (!nextInvocation) nextInvocation = delay.ready.then(invoke)63 return nextInvocation64 }65 wrapper.cancel = async (): Promise<void> => {66 const _lastInvocationDone = lastInvocationDone67 delay.cancel()68 nextInvocation = null69 nextArgs = null70 lastInvocationDone = Promise.resolve()71 delay = new Delay(lastInvocationDone, 0)72 await _lastInvocationDone73 }74 wrapper.flush = async (): Promise<void> => {75 delay.flush()76 await lastInvocationDone77 }78 return wrapper79}...
debounce.test.js
Source:debounce.test.js
1/* Any copyright is dedicated to the Public Domain.2 * http://creativecommons.org/publicdomain/zero/1.0/ */3"use strict";4const expect = require("expect");5const {6 debounceActions,7} = require("devtools/client/shared/redux/middleware/debounce");8describe("Debounce Middleware", () => {9 let nextArgs = [];10 const fakeStore = {};11 const fakeNext = (...args) => {12 nextArgs.push(args);13 };14 beforeEach(() => {15 nextArgs = [];16 });17 it("should pass the intercepted action to next", () => {18 const fakeAction = {19 type: "FAKE_ACTION"20 };21 debounceActions()(fakeStore)(fakeNext)(fakeAction);22 expect(nextArgs.length).toEqual(1);23 expect(nextArgs[0]).toEqual([fakeAction]);24 });25 it("should debounce if specified", () => {26 const fakeAction = {27 type: "FAKE_ACTION",28 meta: {29 debounce: true30 }31 };32 const executed = debounceActions(1, 1)(fakeStore)(fakeNext)(fakeAction);33 expect(nextArgs.length).toEqual(0);34 return executed.then(() => {35 expect(nextArgs.length).toEqual(1);36 });37 });38 it("should have no effect if no timeout", () => {39 const fakeAction = {40 type: "FAKE_ACTION",41 meta: {42 debounce: true43 }44 };45 debounceActions()(fakeStore)(fakeNext)(fakeAction);46 expect(nextArgs.length).toEqual(1);47 expect(nextArgs[0]).toEqual([fakeAction]);48 });...
Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3 {4 {5 is: {6 }7 }8 }9};10mb.create(imposter).then(function (api) {11 api.get('/').then(function (response) {12 console.log(response.body);13 api.get('/').then(function (response) {14 console.log(response.body);15 api.stop();16 });17 });18});19mb.create(imposter).then(function (api) {20 return api.get('/').then(function (response) {21 console.log(response.body);22 return api.get('/');23 });24}).then(function (response) {25 console.log(response.body);26 return api.stop();27});
Using AI Code Generation
1var mb = require('mountebank'),2 assert = require('assert'),3 {4 {5 {6 is: {7 }8 },9 {10 is: {11 }12 }13 }14 }15 ];16mb.create({ port: port }, function (error, mb) {17 mb.post('/imposters', imposters, function (error, response) {18 assert.strictEqual(response.statusCode, 201);19 mb.get('/imposters/3000', function (error, response) {20 assert.strictEqual(response.statusCode, 200);21 assert.strictEqual(response.body.stubs[0].responses[0].is.body, 'first response');22 assert.strictEqual(response.body.stubs[0].responses[1].is.body, 'second response');23 mb.nextArgs('/imposters/3000', function (error, response) {24 assert.strictEqual(response.statusCode, 200);25 assert.strictEqual(response.body.stubs[0].responses[0].is.body, 'second response');26 assert.strictEqual(response.body.stubs[0].responses[1].is.body, 'first response');27 mb.stop();28 });29 });30 });31});32{33 "dependencies": {34 },35 "devDependencies": {36 },37 "scripts": {38 },39}
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const imposters = {4 stubs: [{5 responses: [{6 is: {7 headers: {8 },9 body: JSON.stringify({10 })11 }12 }]13 }]14};15mb.create(port, imposters)16 .then(function (response) {17 console.log(response);18 })19 .catch(function (response) {20 console.log(response);21 });22const mb = require('mountebank');23const port = 2525;24const imposters = {25 stubs: [{26 responses: [{27 is: {28 headers: {29 },30 body: JSON.stringify({31 })32 }33 }]34 }]35};36mb.create(port, imposters)37 .then(function (response) {38 console.log(response);39 .then(function (response) {40 console.log(response);41 })42 .catch(function (response) {43 console.log(response);44 });45 })46 .catch(function (response) {47 console.log(response);48 });
Using AI Code Generation
1var mb = require('mountebank');2var logger = require('winston');3var port = 2525;4var imposter = {5 {6 {7 "is": {8 }9 }10 }11};12mb.create(imposter, function (error, mb) {13 if (error) {14 logger.error(error);15 }16 else {17 logger.info('Imposter created at: ' + imposterUrl);18 mb.nextArgs(function (error, args) {19 if (error) {20 logger.error(error);21 }22 else {23 logger.info('nextArgs: ' + JSON.stringify(args));24 }25 });26 }27});28var mb = require('mountebank');29var logger = require('winston');30var port = 2525;31var imposter = {32 {33 {34 "is": {35 }36 }37 }38};39mb.create(imposter, function (error, mb) {40 if (error) {41 logger.error(error);42 }43 else {44 logger.info('Imposter created at: ' + imposterUrl);45 mb.nextArgs(function (error, args) {46 if (error) {47 logger.error(error);48 }49 else {50 logger.info('nextArgs: ' + JSON.stringify(args));51 }52 });53 }54});55var mb = require('mountebank');56var logger = require('winston');57var port = 2525;58var imposter = {59 {60 {61 "is": {62 }
Using AI Code Generation
1var mb = require('mountebank');2var Q = require('q');3var port = 2525;4var protocol = 'http';5var host = 'localhost';6var imposter = {7 {8 {9 is: {10 }11 }12 }13};14mb.create().then(function (api) {15 return api.post('/imposters', imposter).then(function (response) {16 return api.get('/imposters/' + response.body.port);17 }).then(function (response) {18 console.log(response.body.stubs[0].responses[0].body);19 return api.del('/imposters/' + response.body.port);20 });21});22var mb = require('mountebank');23var Q = require('q');24var port = 2525;25var protocol = 'http';26var host = 'localhost';27var imposter = {28 {29 {30 is: {31 }32 }33 }34};35mb.create().then(function (api) {36 return api.post('/imposters', imposter).then(function (response) {37 return api.get('/imposters/' + response.body.port);38 }).then(function (response) {39 console.log(response.body.stubs[0].responses[0].body);40 return api.del('/imposters/' + response.body.port);41 });42});43var mb = require('mountebank');44var Q = require('q');45var port = 2525;46var protocol = 'http';47var host = 'localhost';48var imposter = {49 {50 {51 is: {52 }53 }54 }55};56mb.create().then(function (api) {57 return api.post('/imposters', imposter).then
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const protocol = 'http';4const host = 'localhost';5const stubs = [{6 predicates: [{7 equals: {8 }9 }],10 responses: [{11 is: {12 }13 }]14}];15const imposter = {16};17mb.create(imposter).then(function (imposter) {18 console.log('Imposter created at %s:%s', host, port);19 console.log(imposter);20 return imposter.nextArgs();21}).then(function (args) {22 console.log('Next request received at %s:%s', host, port);23 console.log(args);24 return mb.stop();25}).then(function () {26 console.log('Shutdown successful');27}).catch(function (error) {28 console.error('Error: %s', error.message);29});30const mb = require('mountebank');31const port = 2525;32const protocol = 'http';33const host = 'localhost';34const stubs = [{35 predicates: [{36 equals: {37 }38 }],39 responses: [{40 is: {41 }42 }]43}];44const imposter = {45};46mb.create(imposter).then(function (imposter) {47 console.log('Imposter created at %s:%s', host, port);48 console.log(imposter);49 return imposter.nextArgs();50}).then(function (args) {51 console.log('Next request received at %s:%s', host, port);52 console.log(args);53 return mb.stop();54}).then(function () {55 console.log('Shutdown successful');56}).catch(function (error) {57 console.error('Error: %s', error.message);58});59const mb = require('mountebank');60const port = 2525;61const protocol = 'http';62const host = 'localhost';63const stubs = [{
Using AI Code Generation
1var mb = require('mountebank');2var logger = require('winston');3var config = require('./config');4var fs = require('fs');5var PORT = config.port;6var IMPOSTER = config.imposter;7var PROXY = config.proxy;8var PROXY_PORT = config.proxyPort;9var PROXY_PROTOCOL = config.proxyProtocol;10var PROXY_TO = config.proxyTo;11var PROXY_TO_PORT = config.proxyToPort;12var PROXY_TO_PROTOCOL = config.proxyToProtocol;13var PROXY_TO_PATH = config.proxyToPath;14var PREDICATE = config.predicate;15var PREDICATE_METHOD = config.predicateMethod;16var PREDICATE_PATH = config.predicatePath;17var PREDICATE_HEADERS = config.predicateHeaders;18var PREDICATE_HEADERS_NAME = config.predicateHeadersName;19var PREDICATE_HEADERS_VALUE = config.predicateHeadersValue;20var RESPONSE = config.response;21var RESPONSE_IS = config.responseIs;22var RESPONSE_HEADERS = config.responseHeaders;23var RESPONSE_HEADERS_NAME = config.responseHeadersName;24var RESPONSE_HEADERS_VALUE = config.responseHeadersValue;25var RESPONSE_BODY = config.responseBody;26var RESPONSE_BODY_TEXT = config.responseBodyText;27var RESPONSE_BODY_FILE = config.responseBodyFile;28var RESPONSE_BODY_FILE_PATH = config.responseBodyFilePath;29var RESPONSE_BODY_FILE_ENCODING = config.responseBodyFileEncoding;30var RESPONSE_BODY_FILE_MIME = config.responseBodyFileMime;31var RESPONSE_BODY_MODE = config.responseBodyMode;32var RESPONSE_BODY_MODE_FILE = config.responseBodyModeFile;33var RESPONSE_BODY_MODE_TEXT = config.responseBodyModeText;34var imposter = {35 {36 {37 equals: {38 headers: {39 }40 }41 }42 {43 is: {44 headers: {45 },46 body: {47 }48 }49 }50 }51};52mb.create({port: PORT, pidfile: 'mb.pid', logfile: 'mb.log', loglevel: 'debug'}, function (error, mbServer) {53 if (error) {54 console.log('Error
Using AI Code Generation
1var mb = require('mountebank');2var assert = require('assert');3mb.start({4}, function () {5 var imposter = {6 {7 {8 equals: {9 }10 }11 {12 is: {13 }14 }15 }16 };17 mb.post('/imposters', imposter, function (error, response) {18 assert.strictEqual(response.statusCode, 201);19 var args = [1, 2, 3];20 var options = {21 headers: {22 },23 data: JSON.stringify(args)24 };25 mb.nextArgs('/imposters/4545', options, function (error, response) {26 assert.strictEqual(response.statusCode, 200);27 assert.strictEqual(response.body, 'OK');28 mb.del('/imposters/4545', function () {29 mb.stop();30 });31 });32 });33});34{35 "dependencies": {36 },37 "devDependencies": {},38 "scripts": {39 },40}
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!!