Best JavaScript code snippet using mountebank
iwc-signalr.js
Source:iwc-signalr.js  
1//https://github.com/slimjack/IWC-SignalR2(function (scope) {3    var registeredProxies = {};4    var isConnectionOwner = false;5    var isSynchronized = false;6    var isInitialized = false;7    var deferredStartResult = $.Deferred();8    var serverInvocationDeferredResults = {};9    var lsPrefix = SJ.iwc.getLocalStoragePrefix() + '_SIGNALR_';10    var proxyClientsConfig = new SJ.iwc.SharedData(lsPrefix + 'CLIENTS');11    var iwcSignalRVersion = '0.1';12    SJ.localStorage.setVersion(lsPrefix, iwcSignalRVersion);13    //region Utility functions14    function forwardDefferedEvents(targetDeferred, srcPromise) {15        srcPromise.done(function () {16            targetDeferred.resolveWith(this, arguments);17        });18        srcPromise.fail(function () {19            targetDeferred.rejectWith(this, arguments);20        });21        srcPromise.progress(function () {22            targetDeferred.notifyWith(this, arguments);23        });24    };25    //endregion26    //region Init27    function init() {28        if (isInitialized) {29            return;30        }31        isInitialized = true;32        SJ.windowOn('unload', function () {33            if (isConnectionOwner) {34                SJ.localStorage.removeItem(lsPrefix + 'STARTEDRESULT');35                $.connection.hub.stop();36            }37        });38        SJ.iwc.EventBus.on('signalrclientinvoke', onClientInvoke, null, true);39        SJ.iwc.EventBus.on('signalrserverresponse', onServerResponse, null, true);40        SJ.iwc.EventBus.on('signalrconnectionstarted', onConnectionStarted, null, true);41        SJ.iwc.EventBus.on('signalrstatechanged', onStateChanged, null, true);42        SJ.iwc.EventBus.on('signalrconnectionstarting', onStarting, null, true);43        SJ.iwc.EventBus.on('signalrconnectionreceived', onReceived, null, true);44        SJ.iwc.EventBus.on('signalrconnectionslow', onConnectionSlow, null, true);45        SJ.iwc.EventBus.on('signalrconnectionreconnecting', onReconnecting, null, true);46        SJ.iwc.EventBus.on('signalrconnectionreconnected', onReconnected, null, true);47        SJ.iwc.EventBus.on('signalrconnectiondisconnected', onDisconnected, null, true);48    };49    //endregion50    //region Hub starting51    function start() {52        init();53        var startArgs = Array.prototype.slice.call(arguments, 0);54        if (isConnectionOwner) {55            var result = $.connection.hub.start.apply($.connection.hub, startArgs);56            onHubDeferredStart(result);57            return result;58        } else {59            var result = $.Deferred();60            SJ.iwc.WindowMonitor.onReady(function () {61                updateDeferredStartResult();62                if (!isSynchronized) {63                    isSynchronized = true;64                    SJ.lock('IWC_SIGNALR', function () {65                        isConnectionOwner = true;66                        proxyClientsConfig.onChanged(function (data) {67                            if (!data) {68                                return;69                            }70                            if (applyProxyClientsConfig(data)) {71                                onHubDeferredStart($.connection.hub.start.apply($.connection.hub, startArgs));72                            }73                        });74                        var clientsConfig = proxyClientsConfig.get();75                        if (clientsConfig) {76                            clientsConfig = removeObsoleteClientsConfigs(clientsConfig);77                            applyProxyClientsConfig(clientsConfig);78                            proxyClientsConfig.change(removeObsoleteClientsConfigs);79                        }80                        subscribeOnServerRequests();81                        configureRealHubProxies();82                        subscribeConnectionEvents();83                        onHubDeferredStart($.connection.hub.start.apply($.connection.hub, startArgs));84                    });85                }86                forwardDefferedEvents(result, deferredStartResult.promise());87            });88            return result.promise();89        }90    };91    function updateDeferredStartResult() {92        var startedResult = getConnectionStartedResult();93        if (startedResult) {94            if (!isStartedResultEqualToDeferred(startedResult.success)) {95                deferredStartResult = $.Deferred();96            }97            if (startedResult.success) {98                deferredStartResult.resolve();99            } else {100                deferredStartResult.reject(startedResult.errorMsg);101            }102        } else if (deferredStartResult.state() !== "pending") {103            deferredStartResult = $.Deferred();104        }105    };106    function subscribeConnectionEvents() {107        $.connection.hub.starting(function () {108            SJ.iwc.EventBus.fire('signalrconnectionstarting');109        });110        $.connection.hub.received(function () {111            SJ.iwc.EventBus.fire('signalrconnectionreceived');112        });113        $.connection.hub.connectionSlow(function () {114            SJ.iwc.EventBus.fire('signalrconnectionslow');115        });116        $.connection.hub.reconnecting(function () {117            SJ.iwc.EventBus.fire('signalrconnectionreconnecting');118        });119        $.connection.hub.reconnected(function () {120            SJ.iwc.EventBus.fire('signalrconnectionreconnected');121        });122        $.connection.hub.disconnected(function () {123            SJ.iwc.EventBus.fire('signalrconnectiondisconnected');124        });125        $.connection.hub.stateChanged(onHubStateChanged);126    };127    function onHubDeferredStart(deferredResult) {128        deferredResult.done(function () {129            onHubConnectionStarted(true);130        })131        .fail(function (errorMsg) {132            onHubConnectionStarted(false, errorMsg);133        });134    };135    function onConnectionStarted(success, errorMessage) {136        if (success) {137            deferredStartResult.resolve();138        } else {139            deferredStartResult.reject(errorMessage);140        }141    };142    function getConnectionStartedResult() {143        var startedResult = null;144        var serializedData = SJ.localStorage.getItem(lsPrefix + 'STARTEDRESULT');145        if (serializedData) {146            startedResult = JSON.parse(serializedData);147            if (!SJ.iwc.WindowMonitor.isWindowOpen(startedResult.windowId)) {148                startedResult = null;149            }150        }151        return startedResult;152    };153    function isStartedResultEqualToDeferred(startedResultSuccess) {154        var deferredStartResultState = deferredStartResult.state();155        var deferredStartResultSuccess = deferredStartResultState === 'resolved';156        return (deferredStartResultState === "pending") || (startedResultSuccess === deferredStartResultSuccess);157    };158    function onHubConnectionStarted(success, errorMsg) {159        if (!isConnectionOwner)160            throw "Invalid operation - onHubConnectionStarted is allowed only for connection owner";161        var startedResult = {162            success: success,163            errorMsg: errorMsg,164            windowId: SJ.iwc.WindowMonitor.getThisWindowId()165        };166        SJ.localStorage.setItem(lsPrefix + 'STARTEDRESULT', JSON.stringify(startedResult));167        SJ.iwc.EventBus.fire('signalrconnectionstarted', success, errorMsg);168    };169    function configureRealHubProxies() {170        for (var proxyName in registeredProxies) {171            if (registeredProxies.hasOwnProperty(proxyName)) {172                configureRealProxyClient(registeredProxies[proxyName]);173            }174        }175    };176    function subscribeOnServerRequests() {177        SJ.iwc.EventBus.on('signalrserverinvoke', onServerInvoke, null, true);178    };179    //endregion180    //region Hub proxy181    function getHubProxy(proxyName, proxyConfig) {182        var hubProxy;183        if (registeredProxies[proxyName]) {184            var client = registeredProxies[proxyName].client;185            for (var propName in client) {186                if (SJ.isFunction(proxyConfig.client[propName]) && client[propName] === SJ.emptyFn) {187                    client[propName] = proxyConfig.client[propName];188                }189            }190            for (var propName in proxyConfig.client) {191                if (SJ.isFunction(proxyConfig.client[propName]) && !client[propName]) {192                    client[propName] = proxyConfig.client[propName];193                }194            }195            hubProxy = registeredProxies[proxyName];196        } else {197            hubProxy = {198                name: proxyName,199                client: proxyConfig.client,200                server: getProxyServer(proxyName)201            };202            registeredProxies[proxyName] = hubProxy;203        }204        proxyClientsConfig.change(function (data) {205            data = data || {};206            data[proxyName] = data[proxyName] || { windows: [], methods: [] };207            var windows = data[proxyName].windows;208            var thisWindowId = SJ.iwc.WindowMonitor.getThisWindowId();209            if (windows.indexOf(thisWindowId) === -1) {210                windows.push(thisWindowId);211            }212            var methods = data[proxyName].methods;213            for (var propName in proxyConfig.client) {214                if (proxyConfig.client.hasOwnProperty(propName) && SJ.isFunction(proxyConfig.client[propName])) {215                    if (methods.indexOf(propName) === -1) {216                        methods.push(propName);217                    }218                }219            }220            return data;221        });222        return hubProxy;223    };224    function applyProxyClientsConfig(data) {225        var isConfigChanged = false;226        for (var proxyName in data) {227            if (data.hasOwnProperty(proxyName)) {228                var proxy = registeredProxies[proxyName];229                if (!proxy) {230                    proxy = {231                        name: proxyName,232                        client: {},233                        server: getProxyServer(proxyName)234                    };235                    registeredProxies[proxyName] = proxy;236                }237                data[proxyName].methods.forEach(function (methodName) {238                    if (!proxy.client[methodName]) {239                        isConfigChanged = true;240                        proxy.client[methodName] = SJ.emptyFn;241                    } else if (!proxy.client._applied || !proxy.client._applied[methodName]) {242                        isConfigChanged = true;243                    }244                });245            }246        }247        if (isConfigChanged) {248            configureRealHubProxies();249        }250        return isConfigChanged;251    };252    function removeObsoleteClientsConfigs(clientsConfig) {253        for (var proxyName in clientsConfig) {254            if (clientsConfig.hasOwnProperty(proxyName)) {255                var isConfigChanged = false;256                var filteredWindows = [];257                clientsConfig[proxyName].windows.forEach(function (windowId) {258                    if (SJ.iwc.WindowMonitor.isWindowOpen(windowId)) {259                        filteredWindows.push(windowId);260                    } else {261                        isConfigChanged = true;262                    }263                });264                if (isConfigChanged) {265                    if (filteredWindows.length) {266                        clientsConfig[proxyName].windows = filteredWindows;267                    } else {268                        delete clientsConfig[proxyName];269                    }270                }271            }272        }273        return clientsConfig;274    };275    function configureRealProxyClient(proxy) {276        var realProxy = $.connection[proxy.name];277        for (var propName in proxy.client) {278            if (proxy.client.hasOwnProperty(propName) && SJ.isFunction(proxy.client[propName]) && !realProxy.client[propName]) {279                configureRealProxyClientMethod(proxy, realProxy, propName);280                proxy.client._applied = proxy.client._applied || {};281                proxy.client._applied[propName] = true;282            }283        }284    };285    function configureRealProxyClientMethod(proxy, realProxy, methodName) {286        realProxy.client[methodName] = function () {287            proxy.client[methodName].apply(this, arguments);288            var eventArgs = ['signalrclientinvoke', proxy.name, methodName].concat(Array.prototype.slice.call(arguments, 0));289            SJ.iwc.EventBus.fire.apply(SJ.iwc.EventBus, eventArgs);290        };291    }292    function onClientInvoke(proxyName, methodname) {293        if (!isConnectionOwner && registeredProxies[proxyName] && registeredProxies[proxyName].client[methodname]) {294            var args = Array.prototype.slice.call(arguments, 2);295            registeredProxies[proxyName].client[methodname].apply(registeredProxies[proxyName], args);296        }297    }298    function getProxyServer(proxyName) {299        var realProxy = $.connection[proxyName];300        var proxySrever = {};301        for (var propName in realProxy.server) {302            if (realProxy.server.hasOwnProperty(propName) && SJ.isFunction(realProxy.server[propName])) {303                proxySrever[propName] = getWrappedProxyServerFn(proxyName, propName);304            }305        }306        return proxySrever;307    };308    function getWrappedProxyServerFn(proxyName, methodName) {309        var realProxy = $.connection[proxyName];310        return function () {311            if (isConnectionOwner) {312                return realProxy.server[methodName].apply(realProxy.server, arguments);313            } else {314                var args = Array.prototype.slice.call(arguments, 0);315                return invokeServerMethod(proxyName, methodName, args);316            }317        };318    };319    function invokeServerMethod(proxyName, methodName, args) {320        var requestId = SJ.generateGUID();321        var eventArgs = ['signalrserverinvoke', proxyName, methodName, requestId].concat(args);322        SJ.iwc.EventBus.fire.apply(SJ.iwc.EventBus, eventArgs);323        var deferredResult = $.Deferred();324        serverInvocationDeferredResults[requestId] = deferredResult;325        return deferredResult.promise();326    };327    function onServerInvoke(proxyName, methodName, requestId) {328        var args = Array.prototype.slice.call(arguments, 3);329        if (registeredProxies[proxyName]) {330            registeredProxies[proxyName].server[methodName].apply(registeredProxies[proxyName], args)331                .done(function () {332                    var eventArgs = ['signalrserverresponse', requestId, true].concat(Array.prototype.slice.call(arguments, 0));333                    SJ.iwc.EventBus.fire.apply(SJ.iwc.EventBus, eventArgs);334                })335                .fail(function (errorMsg) {336                    SJ.iwc.EventBus.fire('signalrserverresponse', requestId, false, errorMsg);337                });338        }339    }340    function onServerResponse(requestId, success, errorMsg) {341        if (!isConnectionOwner && serverInvocationDeferredResults[requestId]) {342            if (success) {343                var args = Array.prototype.slice.call(arguments, 2);344                serverInvocationDeferredResults[requestId].resolve.apply(serverInvocationDeferredResults[requestId], args);345            } else {346                serverInvocationDeferredResults[requestId].reject(errorMsg);347            }348            delete serverInvocationDeferredResults[requestId];349        }350    };351    //endregion352    //region Connection state353    function onStateChanged(newState, prevState) {354        observable.fire('statechanged', newState, prevState);355        if (newState !== prevState && newState === $.signalR.connectionState.connected) {356            observable.fire('connected');357        }358    };359    function onStarting() {360        observable.fire('starting');361    };362    function onReceived() {363        observable.fire('received');364    };365    function onConnectionSlow() {366        observable.fire('connectionslow');367    };368    function onReconnecting() {369        observable.fire('reconnecting');370    };371    function onReconnected() {372        observable.fire('reconnected');373    };374    function onDisconnected() {375        observable.fire('disconnected');376    };377    function onHubStateChanged(changes) {378        updateState(changes.newState);379        SJ.iwc.EventBus.fire('signalrstatechanged', changes.newState, changes.oldState);380    };381    function updateState(state) {382        if (!isConnectionOwner)383            throw "Invalid operation - updateState is allowed only for connection owner";384        var stateData = {385            state: state,386            connectionId: $.connection.hub.id,387            windowId: SJ.iwc.WindowMonitor.getThisWindowId()388        };389        SJ.localStorage.setItem(lsPrefix + 'STATE', JSON.stringify(stateData));390    };391    function getStateData() {392        var result = null;393        var serializedData = SJ.localStorage.getItem(lsPrefix + 'STATE');394        if (serializedData) {395            var stateData = JSON.parse(serializedData);396            if (SJ.iwc.WindowMonitor.isWindowOpen(stateData.windowId)) {397                result = stateData;398            }399        }400        return result;401    };402    function getState() {403        var state = $.connection.connectionState.disconnected;404        var stateData = getStateData();405        if (stateData) {406            state = stateData.state;407        }408        return state;409    };410    function getConnectionId() {411        var result = null;412        var stateData = getStateData();413        if (stateData) {414            result = stateData.connectionId;415        }416        return result;417    };418    function getConnectionOwnerWindowId() {419        var result = null;420        var serializedData = SJ.localStorage.getItem(lsPrefix + 'STATE');421        if (serializedData) {422            var stateData = JSON.parse(serializedData);423            if (SJ.iwc.WindowMonitor.isWindowOpen(stateData.windowId)) {424                result = stateData.windowId;425            }426        }427        return result;428    };429    //endregion430    var IWCSignalR = {431        getHubProxy: getHubProxy,432        start: start,433        getState: getState,434        getConnectionId: getConnectionId,435        isConnectionOwner: function() {436             return isConnectionOwner;437        },438        getConnectionOwnerWindowId: getConnectionOwnerWindowId439    };440    var observable = SJ.utils.Observable.decorate(IWCSignalR, true);441    SJ.copy(scope, IWCSignalR);...puremvc.d.ts
Source:puremvc.d.ts  
1declare module puremvc2{3	export interface ICommand4		extends INotifier5	{6		execute( notification:INotification ):void;7	}8	export interface IController9	{10		executeCommand( notification:INotification ):void;11		registerCommand( notificationName:string, commandClassRef:Function ):void;12		hasCommand( notificationName:string ):bool;13		removeCommand( notificationName:string ):void;14	}15	export interface IFacade16		extends INotifier17	{18		registerCommand( notificationName:string, commandClassRef:Function ):void;19		removeCommand( notificationName:string ): void;20		hasCommand( notificationName:string ):bool;21		registerProxy( proxy:IProxy ):void;22		retrieveProxy( proxyName:string ):IProxy;23		removeProxy( proxyName:string ):IProxy;24		hasProxy( proxyName:string ):bool;25		registerMediator( mediator:IMediator ):void;26		retrieveMediator( mediatorName:string ):IMediator;27		removeMediator( mediatorName:string ):IMediator;28		hasMediator( mediatorName:string ):bool;29		notifyObservers( notification:INotification ):void;30	}31	export interface IMediator32		extends INotifier33	{34		getMediatorName():string;35		getViewComponent():any;36		setViewComponent( viewComponent:any ):void;37		listNotificationInterests( ):string[];38		handleNotification( notification:INotification ):void;39		onRegister():void;40		onRemove():void;41	}42	export interface IModel43	{44		registerProxy( proxy:IProxy ):void;45		removeProxy( proxyName:string ):IProxy;46		retrieveProxy( proxyName:string ):IProxy;47		hasProxy( proxyName:string ):bool;48	}49	export interface INotification50	{51		getName():string;52		setBody( body:any ):void;53		getBody():any;54		setType( type:string ):void;55		getType():string;56		toString():string;57	}58	export interface INotifier59	{60		sendNotification( name:string, body?:any, type?:string ):void;61	}62	export interface IObserver63	{64		setNotifyMethod( notifyMethod:Function ):void;65		setNotifyContext( notifyContext:any ):void;66		notifyObserver( notification:INotification ):void;67		compareNotifyContext( object:any ):bool;68	}69	export interface IProxy70		extends INotifier71	{72		getProxyName():string;73		setData( data:any ):void;74		getData():any;75		onRegister( ):void;76		onRemove( ):void;77	}78	export interface IView79	{80		registerObserver( notificationName:string, observer:IObserver ):void;81		removeObserver( notificationName:string, notifyContext:any ):void;82		notifyObservers( notification:INotification ):void;83		registerMediator( mediator:IMediator ):void;84		retrieveMediator( mediatorName:string ):IMediator;85		removeMediator( mediatorName:string ):IMediator;86		hasMediator( mediatorName:string ):bool;87	}88    export class Observer89		implements IObserver90	{91        public notify: Function;92        public context: any;93        constructor (notifyMethod: Function, notifyContext: any);94        private getNotifyMethod(): Function;95        public setNotifyMethod(notifyMethod: Function): void;96        private getNotifyContext(): any;97        public setNotifyContext(notifyContext: any): void;98        public notifyObserver(notification: INotification): void;99        public compareNotifyContext(object: any): bool;100    }101	102	export class View103		implements IView104	{105        public mediatorMap: Object;106        public observerMap: Object;107        constructor ();108        public initializeView(): void;109        public registerObserver(notificationName: string, observer: IObserver): void;110        public removeObserver(notificationName: string, notifyContext: any): void;111        public notifyObservers(notification: INotification): void;112        public registerMediator(mediator: IMediator): void;113        public retrieveMediator(mediatorName: string): IMediator;114        public removeMediator(mediatorName: string): IMediator;115        public hasMediator(mediatorName: string): bool;116        static SINGLETON_MSG: string;117        static instance: IView;118        static getInstance(): IView;119    }120    export class Controller121		implements IController122	{123        public view: IView;124        public commandMap: Object;125        constructor ();126        public initializeController(): void;127        public executeCommand(notification: INotification): void;128        public registerCommand(notificationName: string, commandClassRef: Function): void;129        public hasCommand(notificationName: string): bool;130        public removeCommand(notificationName: string): void;131        static instance: IController;132        static SINGLETON_MSG: string;133        static getInstance(): IController;134    }135    export class Model136		implements IModel137	{138        public proxyMap: Object;139        constructor ();140        public initializeModel(): void;141        public registerProxy(proxy: IProxy): void;142        public removeProxy(proxyName: string): IProxy;143        public retrieveProxy(proxyName: string): IProxy;144        public hasProxy(proxyName: string): bool;145        static SINGLETON_MSG: string;146        static instance: IModel;147        static getInstance(): IModel;148    }149    export class Notification150		implements INotification151	{152        public name: string;153        public body: any;154        public type: string;155        constructor (name: string, body?: any, type?: string);156        public getName(): string;157        public setBody(body: any): void;158        public getBody(): any;159        public setType(type: string): void;160        public getType(): string;161        public toString(): string;162    }163    export class Facade164		implements IFacade165	{166        public model: IModel;167        public view: IView;168        public controller: IController;169        constructor ();170        public initializeFacade(): void;171        public initializeModel(): void;172        public initializeController(): void;173        public initializeView(): void;174        public registerCommand(notificationName: string, commandClassRef: Function): void;175        public removeCommand(notificationName: string): void;176        public hasCommand(notificationName: string): bool;177        public registerProxy(proxy: IProxy): void;178        public retrieveProxy(proxyName: string): IProxy;179        public removeProxy(proxyName: string): IProxy;180        public hasProxy(proxyName: string): bool;181        public registerMediator(mediator: IMediator): void;182        public retrieveMediator(mediatorName: string): IMediator;183        public removeMediator(mediatorName: string): IMediator;184        public hasMediator(mediatorName: string): bool;185        public notifyObservers(notification: INotification): void;186        public sendNotification(name: string, body?: any, type?: string): void;187        static SINGLETON_MSG: string;188        static instance: IFacade;189        static getInstance(): IFacade;190    }191    export class Notifier192		implements INotifier193	{194        public facade: IFacade;195        constructor ();196        public sendNotification(name: string, body?: any, type?: string): void;197    }198    export class MacroCommand199		extends Notifier200		implements ICommand, INotifier201	{202        public subCommands: Function[];203        constructor ();204        public initializeMacroCommand(): void;205        public addSubCommand(commandClassRef: Function): void;206        public execute(notification: INotification): void;207    }208    export class SimpleCommand209		extends Notifier210		implements ICommand, INotifier211	{212        public execute(notification: INotification): void;213    }214    export class Mediator215		extends Notifier216		implements IMediator, INotifier217	{218        public mediatorName: string;219        public viewComponent: any;220        constructor (mediatorName?: string, viewComponent?: any);221        public getMediatorName(): string;222        public getViewComponent(): any;223        public setViewComponent(viewComponent: any): void;224        public listNotificationInterests(): string[];225        public handleNotification(notification: INotification): void;226        public onRegister(): void;227        public onRemove(): void;228        static NAME: string;229    }230    export class Proxy231		extends Notifier232		implements IProxy, INotifier233	{234        public proxyName: string;235        public data: any;236        constructor (proxyName?: string, data?: any);237        public getProxyName(): string;238        public setData(data: any): void;239        public getData(): any;240        public onRegister(): void;241        public onRemove(): void;242        static NAME: string;243    }...Using AI Code Generation
1var request = require('request');2var options = {3  json: {4      {5          {6            "is": {7              "headers": {8              },9            }10          }11      }12  }13};14request(options, function (error, response, body) {15  if (!error && response.statusCode == 201) {16    console.log(body);17  }18});Using AI Code Generation
1var mb = require('mountebank');2var proxy = mb.create({ port: 2525, ip: 'localhost', allowInjection: true });3proxy.then(function (api) {4    api.post('/imposters', {5            {6                    {7                        is: {8                            headers: {9                            },10                            body: {11                            }12                        }13                    }14            }15    }).then(function (response) {16        api.get('/imposters').then(function (response) {17            console.log(response.body);18        });19    });20});21var mb = require('mountebank');22var proxy = mb.create({ port: 2525, ip: 'localhost', allowInjection: true });23proxy.then(function (api) {24    api.post('/imposters', {25            {26                    {27                        is: {28                            headers: {29                            },30                            body: {31                            }32                        }33                    }34            }35    }).then(function (response) {36        api.get('/imposters').then(function (response) {37            console.log(response.body);38        });39    });40});41var mb = require('mountebank');42var proxy = mb.create({ port: 2525, ip: 'localhost', allowInjection: true });43proxy.then(function (api) {44    api.post('/imposters', {45            {46                    {47                        is: {48                            headers: {49                            },50                            body: {51                            }52                        }53                    }Using AI Code Generation
1const mb = require('mountebank');2const proxy = mb.create({port: 2525, allowInjection: true});3proxy.then(function () {4    return proxy.post('/imposters', {5        stubs: [{6            responses: [{7                is: {8                }9            }]10        }]11    });12}).then(function () {13    return proxy.get('/imposters');14}).then(function (response) {15    console.log('All imposters: ', response.body);16}).then(function () {17    return proxy.del('/imposters');18}).then(function () {19    return proxy.del('/imposters');20});21{22  "scripts": {23  },24  "dependencies": {25  }26}27{28  "dependencies": {29    "mountebank": {30      "requires": {Using AI Code Generation
1var assert = require('assert'),2    http = require('http'),3    mb = require('mountebank');4mb.create(2525, function (error) {5    assert.ifError(error);6    var stub = { responses: [{ is: { statusCode: 200, body: 'Hello World!' } }] };7    mb.post('/imposters', { port: 3000, stubs: [stub] }, function (error, response) {8        assert.ifError(error);9            assert.strictEqual(response.statusCode, 200);10            var body = '';11            response.on('data', function (chunk) { body += chunk; });12            response.on('end', function () {13                assert.strictEqual(body, 'Hello World!');14                mb.stop();15            });16        });17    });18});19{20  "scripts": {21  },22  "dependencies": {23  }24}Using AI Code Generation
1var proxy = require('mountebank-proxy');2var mb = proxy.create({host: 'localhost', port: 2525});3mb.get('/imposters', function (err, response) {4  console.log(JSON.parse(response.body));5});6mb.post('/imposters', {7    {8        {is: {body: 'Hello world!'}}9    }10}, function (err, response) {11  console.log(JSON.parse(response.body));12});13var proxy = require('mountebank-proxy');14var mb = proxy.create({host: 'localhost', port: 2525});15mb.get('/imposters', function (err, response) {16  console.log(JSON.parse(response.body));17});18mb.post('/imposters', {19    {20        {is: {body: 'Hello world!'}}21    }22}, function (err, response) {23  console.log(JSON.parse(response.body));24});25var proxy = require('mountebank-proxy');26var mb = proxy.create({host: 'localhost', port: 2525});27mb.get('/imposters', function (err, response) {28  console.log(JSON.parse(response.body));29});30mb.post('/imposters', {31    {32        {is: {body: 'Hello world!'}}33    }34}, function (err, response) {35  console.log(JSON.parse(response.body));36});37var proxy = require('mountebank-proxy');38var mb = proxy.create({host: 'localhost', port: 2525});39mb.get('/imposters', function (err, response) {40  console.log(JSON.parse(response.body));41});42mb.post('/imposters', {43    {44        {is: {Using AI Code Generation
1const proxyName = require('mountebank-proxy-name');2    console.log(name);3});4    console.log(name);5});6    console.log(name);7});8    console.log(name);9});10    console.log(name);11});12    console.log(name);13});14    console.log(name);15});16    console.log(name);17});18    console.log(name);19});20    console.log(name);21});Using AI Code Generation
1var mb = require('mountebank'),2    assert = require('assert'),3    mbHelper = require('./mbHelper'),4    Q = require('q'),5mb.create({ port: mbPort, pidfile: 'mb.pid', logfile: 'mb.log', ipWhitelist: ['*'] }, function (error, imposter) {6    assert.strictEqual(error, null, 'no error when creating mb');7    mbHelper.createStub(mbUrl, 'test', 'test', 'test', 'test')8        .then(function (response) {9            console.log('created stub');10            return mbHelper.createProxy(mbUrl, 'test', 'test', 'test', 'test', 'test');11        })12        .then(function (response) {13            console.log('created proxy');14            return mbHelper.createProxy(mbUrl, 'test', 'test', 'test', 'test', 'test');15        })16        .catch(function (error) {17            console.log('error');18            console.log(error);19        });20});21mbHelper = {22    createStub: function (mbUrl, protocol, host, port, path) {23        var deferred = Q.defer();24        var request = require('request');25        var options = {26            headers: {27            },28            body: JSON.stringify({29                    {30                            {31                                is: {32                                    headers: {33                                    },34                                }35                            }36                    }37            })38        };39        request(options, function (error, response, body) {40            if (!error && response.statusCode == 201) {41                deferred.resolve(body);42            }43            else {44                deferred.reject(error);45            }46        });47        return deferred.promise;48    },49    createProxy: function (mbUrl, protocol, host, port, path, proxyName) {50        var deferred = Q.defer();Using AI Code Generation
1var proxy = require('mountebank-proxy').proxyName('mb1');2proxy.createImposter(2525, { protocol: 'http', name: 'testImposter' }, function (error, imposter) {3    if (error) {4        console.log('error in creating imposter', error);5    }6    else {7        console.log('imposter created', imposter);8    }9});10proxy.deleteImposter(2525, function (error, imposter) {11    if (error) {12        console.log('error in deleting imposter', error);13    }14    else {15        console.log('imposter deleted', imposter);16    }17});18proxy.getImposter(2525, function (error, imposter) {19    if (error) {20        console.log('error in getting imposter', error);21    }22    else {23        console.log('imposter got', imposter);24    }25});26proxy.getImposters(function (error, imposter) {27    if (error) {28        console.log('error in getting imposter', error);29    }30    else {31        console.log('imposter got', imposter);32    }33});34proxy.resetImposters(function (error, imposter) {35    if (error) {36        console.log('error in resetting imposter', error);37    }38    else {39        console.log('imposter reset', imposter);40    }41});42proxy.getAllLogs(function (error, imposter) {43    if (error) {44        console.log('error in getting logs', error);45    }46    else {47        console.log('logs got', imposter);48    }49});50proxy.getImposterLogs(2525, function (error, imposter) {51    if (error) {52        console.log('error in getting logs', error);53    }54    else {55        console.log('logs got', imposter);56    }57});58proxy.resetAllLogs(function (error, imposter) {59    if (error) {60        console.log('error in resetting logs', error);61    }62    else {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!!
