How to use responseConfig method in mountebank

Best JavaScript code snippet using mountebank

responseResolver.js

Source:responseResolver.js Github

copy

Full Screen

1'use strict';2/**3 * Determines the response for a stub based on the user-provided response configuration4 * @module5 */6/**7 * Creates the resolver8 * @param {Object} stubs - The stubs repository9 * @param {Object} proxy - The protocol-specific proxy implementation10 * @param {String} callbackURL - The protocol callback URL for response resolution11 * @returns {Object}12 */13function create (stubs, proxy, callbackURL) {14 // injectState is deprecated in favor of imposterState, but kept for backwards compatibility15 const injectState = {}, // eslint-disable-line no-unused-vars16 pendingProxyResolutions = {},17 inProcessProxy = Boolean(proxy);18 let nextProxyResolutionKey = 0;19 function inject (request, fn, logger, imposterState) {20 const Q = require('q'),21 helpers = require('../util/helpers'),22 deferred = Q.defer(),23 config = {24 request: helpers.clone(request),25 state: imposterState,26 logger: logger,27 callback: deferred.resolve28 },29 compatibility = require('./compatibility');30 compatibility.downcastInjectionConfig(config);31 // Leave parameters for older interface32 const injected = `(${fn})(config, injectState, logger, deferred.resolve, imposterState);`,33 exceptions = require('../util/errors');34 if (request.isDryRun === true) {35 Q.delay(1).then(() => {36 deferred.resolve({});37 });38 }39 else {40 try {41 const response = eval(injected);42 if (helpers.defined(response)) {43 deferred.resolve(response);44 }45 }46 catch (error) {47 logger.error(`injection X=> ${error}`);48 logger.error(` full source: ${JSON.stringify(injected)}`);49 logger.error(` config.request: ${JSON.stringify(config.request)}`);50 logger.error(` config.state: ${JSON.stringify(config.state)}`);51 deferred.reject(exceptions.InjectionError('invalid response injection', {52 source: injected,53 data: error.message54 }));55 }56 }57 return deferred.promise;58 }59 function selectionValue (nodes) {60 const helpers = require('../util/helpers');61 if (!helpers.defined(nodes)) {62 return '';63 }64 else if (!Array.isArray(nodes)) {65 return nodes; // booleans and counts66 }67 else {68 return (nodes.length === 1) ? nodes[0] : nodes;69 }70 }71 function xpathValue (xpathConfig, possibleXML, logger) {72 const xpath = require('./xpath'),73 nodes = xpath.select(xpathConfig.selector, xpathConfig.ns, possibleXML, logger);74 return selectionValue(nodes);75 }76 function jsonpathValue (jsonpathConfig, possibleJSON, logger) {77 const jsonpath = require('./jsonpath'),78 nodes = jsonpath.select(jsonpathConfig.selector, possibleJSON, logger);79 return selectionValue(nodes);80 }81 function buildEquals (request, matchers, valueOf) {82 const result = {},83 isObject = require('../util/helpers').isObject;84 Object.keys(matchers).forEach(key => {85 if (isObject(request[key])) {86 result[key] = buildEquals(request[key], matchers[key], valueOf);87 }88 else {89 result[key] = valueOf(request[key]);90 }91 });92 return result;93 }94 const path = [];95 function buildExists (request, fieldName, matchers, initialRequest) {96 const isObject = require('../util/helpers').isObject,97 setDeep = require('../util/helpers').setDeep;98 Object.keys(request).forEach(key => {99 path.push(key);100 if (isObject(request[key])) {101 buildExists(request[key], fieldName, matchers[key], initialRequest);102 }103 else {104 const booleanValue = (typeof fieldName !== 'undefined' && fieldName !== null && fieldName !== '');105 setDeep(initialRequest, path, booleanValue);106 }107 });108 return initialRequest;109 }110 function predicatesFor (request, matchers, logger) {111 const predicates = [];112 matchers.forEach(matcher => {113 if (matcher.inject) {114 // eslint-disable-next-line no-unused-vars115 const config = { request, logger },116 injected = `(${matcher.inject})(config);`,117 errors = require('../util/errors');118 try {119 predicates.push(...eval(injected));120 }121 catch (error) {122 logger.error(`injection X=> ${error}`);123 logger.error(` source: ${JSON.stringify(injected)}`);124 logger.error(` request: ${JSON.stringify(request)}`);125 throw errors.InjectionError('invalid predicateGenerator injection', { source: injected, data: error.message });126 }127 return;128 }129 const basePredicate = {};130 let hasPredicateOperator = false;131 let predicateOperator; // eslint-disable-line no-unused-vars132 let valueOf = field => field;133 // Add parameters134 Object.keys(matcher).forEach(key => {135 if (key !== 'matches' && key !== 'predicateOperator') {136 basePredicate[key] = matcher[key];137 }138 if (key === 'xpath') {139 valueOf = field => xpathValue(matcher.xpath, field, logger);140 }141 else if (key === 'jsonpath') {142 valueOf = field => jsonpathValue(matcher.jsonpath, field, logger);143 }144 else if (key === 'predicateOperator') {145 hasPredicateOperator = true;146 predicateOperator = matcher[key];147 }148 });149 Object.keys(matcher.matches).forEach(fieldName => {150 const helpers = require('../util/helpers'),151 matcherValue = matcher.matches[fieldName],152 predicate = helpers.clone(basePredicate);153 if (matcherValue === true && hasPredicateOperator === false) {154 predicate.deepEquals = {};155 predicate.deepEquals[fieldName] = valueOf(request[fieldName]);156 }157 else if (hasPredicateOperator === true && matcher.predicateOperator === 'exists') {158 predicate[matcher.predicateOperator] = buildExists(request, fieldName, matcherValue, request);159 }160 else if (hasPredicateOperator === true && matcher.predicateOperator !== 'exists') {161 predicate[matcher.predicateOperator] = valueOf(request);162 }163 else {164 predicate.equals = {};165 predicate.equals[fieldName] = buildEquals(request[fieldName], matcherValue, valueOf);166 }167 predicates.push(predicate);168 });169 });170 return predicates;171 }172 function deepEqual (obj1, obj2) {173 const stringify = require('json-stable-stringify');174 return stringify(obj1) === stringify(obj2);175 }176 function newIsResponse (response, proxyConfig) {177 const result = { is: response };178 const addBehaviors = {};179 if (proxyConfig.addWaitBehavior && response._proxyResponseTime) { // eslint-disable-line no-underscore-dangle180 addBehaviors.wait = response._proxyResponseTime; // eslint-disable-line no-underscore-dangle181 }182 if (proxyConfig.addDecorateBehavior) {183 addBehaviors.decorate = proxyConfig.addDecorateBehavior;184 }185 if (Object.keys(addBehaviors).length > 0) {186 result._behaviors = addBehaviors;187 }188 return result;189 }190 function recordProxyAlways (newPredicates, newResponse, responseConfig) {191 const filter = stubPredicates => deepEqual(newPredicates, stubPredicates);192 return responseConfig.stubIndex().then(index => {193 return stubs.first(filter, index + 1);194 }).then(match => {195 if (match.success) {196 return match.stub.addResponse(newResponse);197 }198 else {199 return stubs.add({ predicates: newPredicates, responses: [newResponse] });200 }201 });202 }203 function recordProxyResponse (responseConfig, request, response, logger) {204 const newPredicates = predicatesFor(request, responseConfig.proxy.predicateGenerators || [], logger),205 newResponse = newIsResponse(response, responseConfig.proxy);206 // proxyTransparent prevents the request from being recorded, and always transparently issues the request.207 if (responseConfig.proxy.mode === 'proxyTransparent') {208 return require('q')();209 }210 else if (responseConfig.proxy.mode === 'proxyOnce') {211 return responseConfig.stubIndex().then(index => {212 return stubs.insertAtIndex({ predicates: newPredicates, responses: [newResponse] }, index);213 });214 }215 else {216 return recordProxyAlways(newPredicates, newResponse, responseConfig);217 }218 }219 function proxyAndRecord (responseConfig, request, logger, requestDetails) {220 const Q = require('q'),221 startTime = new Date(),222 behaviors = require('./behaviors');223 if (['proxyOnce', 'proxyAlways', 'proxyTransparent'].indexOf(responseConfig.proxy.mode) < 0) {224 responseConfig.proxy.mode = 'proxyOnce';225 }226 if (inProcessProxy) {227 return proxy.to(responseConfig.proxy.to, request, responseConfig.proxy, requestDetails).then(response => {228 // eslint-disable-next-line no-underscore-dangle229 response._proxyResponseTime = new Date() - startTime;230 // Run behaviors here to persist decorated response231 return Q(behaviors.execute(request, response, responseConfig._behaviors, logger));232 }).then(response => {233 return recordProxyResponse(responseConfig, request, response, logger).then(() => response);234 });235 }236 else {237 pendingProxyResolutions[nextProxyResolutionKey] = {238 responseConfig: responseConfig,239 request: request,240 startTime: new Date(),241 requestDetails: requestDetails242 };243 nextProxyResolutionKey += 1;244 return Q({245 proxy: responseConfig.proxy,246 request: request,247 callbackURL: `${callbackURL}/${nextProxyResolutionKey - 1}`248 });249 }250 }251 function processResponse (responseConfig, request, logger, imposterState, requestDetails) {252 const Q = require('q'),253 helpers = require('../util/helpers'),254 exceptions = require('../util/errors');255 if (responseConfig.is) {256 // Clone to prevent accidental state changes downstream257 return Q(helpers.clone(responseConfig.is));258 }259 else if (responseConfig.proxy) {260 return proxyAndRecord(responseConfig, request, logger, requestDetails);261 }262 else if (responseConfig.inject) {263 return inject(request, responseConfig.inject, logger, imposterState).then(Q);264 }265 else {266 return Q.reject(exceptions.ValidationError('unrecognized response type',267 { source: helpers.clone(responseConfig) }));268 }269 }270 function hasMultipleTypes (responseConfig) {271 return (responseConfig.is && responseConfig.proxy) ||272 (responseConfig.is && responseConfig.inject) ||273 (responseConfig.proxy && responseConfig.inject);274 }275 /**276 * Resolves a single response277 * @memberOf module:models/responseResolver#278 * @param {Object} responseConfig - The API-provided response configuration279 * @param {Object} request - The protocol-specific request object280 * @param {Object} logger - The logger281 * @param {Object} imposterState - The current state for the imposter282 * @param {Object} options - Additional options not carried with the request283 * @returns {Object} - Promise resolving to the response284 */285 function resolve (responseConfig, request, logger, imposterState, options) {286 const Q = require('q'),287 exceptions = require('../util/errors'),288 helpers = require('../util/helpers'),289 behaviors = require('./behaviors');290 if (hasMultipleTypes(responseConfig)) {291 return Q.reject(exceptions.ValidationError('each response object must have only one response type',292 { source: responseConfig }));293 }294 return processResponse(responseConfig, helpers.clone(request), logger, imposterState, options).then(response => {295 // We may have already run the behaviors in the proxy call to persist the decorated response296 // in the new stub. If so, we need to ensure we don't re-run it297 if (responseConfig.proxy) {298 return Q(response);299 }300 else {301 return Q(behaviors.execute(request, response, responseConfig._behaviors, logger));302 }303 }).then(response => {304 if (inProcessProxy) {305 return Q(response);306 }307 else {308 return responseConfig.proxy ? Q(response) : Q({ response });309 }310 });311 }312 /**313 * Finishes the protocol implementation dance for proxy. On the first call,314 * mountebank selects a JSON proxy response and sends it to the protocol implementation,315 * saving state indexed by proxyResolutionKey. The protocol implementation sends the proxy316 * to the downstream system and calls mountebank again with the response so mountebank317 * can save it and add behaviors318 * @memberOf module:models/responseResolver#319 * @param {Object} proxyResponse - the proxy response from the protocol implementation320 * @param {Number} proxyResolutionKey - the key into the saved proxy state321 * @param {Object} logger - the logger322 * @returns {Object} - Promise resolving to the response323 */324 function resolveProxy (proxyResponse, proxyResolutionKey, logger) {325 const pendingProxyConfig = pendingProxyResolutions[proxyResolutionKey],326 behaviors = require('./behaviors'),327 Q = require('q');328 if (pendingProxyConfig) {329 // eslint-disable-next-line no-underscore-dangle330 proxyResponse._proxyResponseTime = new Date() - pendingProxyConfig.startTime;331 return behaviors.execute(pendingProxyConfig.request, proxyResponse, pendingProxyConfig.responseConfig._behaviors, logger)332 .then(response => {333 return recordProxyResponse(pendingProxyConfig.responseConfig, pendingProxyConfig.request, response, logger)334 .then(() => {335 delete pendingProxyResolutions[proxyResolutionKey];336 return Q(response);337 });338 });339 }340 else {341 const errors = require('../util/errors');342 logger.error('Invalid proxy resolution key: ' + proxyResolutionKey);343 return Q.reject(errors.MissingResourceError('invalid proxy resolution key',344 { source: `${callbackURL}/${proxyResolutionKey}` }));345 }346 }347 return { resolve, resolveProxy };348}...

Full Screen

Full Screen

http-fake.helper.js

Source:http-fake.helper.js Github

copy

Full Screen

1/*2 * HTTP server with programmable API for adding stubs/mocks.3 */4var express = require("express");5var http = require("http");6var expect = require("chai").expect;7// compare a requestMatcher with a request; if each property8// in the requestMatcher matches with a property in the request,9// return true; otherwise, return false10//11// note that chai's eql is abused to do the matches12var meetsCriteria = function (request, requestMatcher) {13 var good = true;14 // if we're recursing into an object in the requestMatcher,15 // but request doesn't have a corresponding object, just16 // return false immediately17 if (!request) {18 return false;19 }20 for (var key in requestMatcher) {21 if (typeof requestMatcher[key] === "function") {22 good = requestMatcher[key](request[key]);23 }24 else if (typeof requestMatcher[key] === "object") {25 good = meetsCriteria(request[key], requestMatcher[key]);26 }27 else {28 try {29 expect(requestMatcher[key]).to.eql(request[key]);30 }31 catch (e) {32 good = false;33 }34 }35 if (!good) {36 break;37 }38 }39 return good;40};41// matches the request req against the requestMatchers in42// map (see Server.map property, below); when a match is found, send it43// via the Express response object res, using the responseConfig in44// the map45var matcher = function (map, req, res) {46 var toSend = null;47 var requestMatcher;48 var responseConfig;49 for (var i = 0; i < map.length; i += 1) {50 requestMatcher = map[i].requestMatcher;51 if (meetsCriteria(req, requestMatcher)) {52 toSend = map[i].responseConfig;53 }54 }55 return toSend;56};57var Server = function () {58 var self = this;59 // this contains objects with the structure60 // {requestMatcher: {...}, responseConfig: {...}};61 // when the server receives a request, it iterates through62 // these objects until it finds a requestMatcher which matches63 // the request; then, it returns a response generated from64 // responseConfig65 this.map = [];66 this.app = express();67 // use middleware to parse request body68 this.app.use(express.bodyParser());69 // hand off requests to the request/response matcher70 this.app.all(/.*/, function (req, res) {71 // defaults if no response config found72 var data = "No matching response for request";73 var statusCode = 503;74 var pause = 0;75 // try to find an appropriate response for this request76 var responseConfig = matcher(self.map, req, res);77 if (responseConfig) {78 statusCode = responseConfig.status || 200;79 // should we generate the response body data using the80 // responseConfig's data function?81 if (typeof responseConfig.data === "function") {82 data = responseConfig.data(req);83 }84 else {85 data = responseConfig.data || '';86 }87 pause = responseConfig.pause || 0;88 }89 else {90 console.error("could not find a response configuration for request");91 }92 setTimeout(function () {93 res.status(statusCode)94 .send(data);95 }, pause);96 });97 this.server = require("http").createServer(this.app);98 this.port = null;99};100// register a fake response for a given request pattern;101// responseConfig specifies how the response should102// be constructed; requestMatcher is an object to compare with103// each received request, to determine if the response is104// an appropriate candidate to return;105// NB if requestMatcher is not specified, the fake response106// will match every request107//108// responseConfig currently uses the following properties:109// * data: sets the response body; this can be set to a function:110// if it is, that function is passed the original express request111// object, and should return a string to be used as the response body112// * status: sets the status code for the response (default: 200)113// * pause: sets a pause (ms) before the response is returned (default: 0)114//115// in the requestMatcher, set a property for each property of the116// request you want to test; the value of the property in the117// requestMatcher can either be a value for comparison (using118// chai's eql() function) or a function which will be passed119// the corresponding value from the request; for example:120//121// {122// query: function (reqQuery) {123// return reqQuery["id"] === "1";124// }125// }126//127// note that if you want requestMatcher to compare headers,128// you should lowercase the names of the headers so they match129// headers as perceived by express; also note that the server130// will parse application/json, multipart/form-data and131// application/x-www-form-urlencoded requests into objects, so132// any matchers for the request body should use objects rather than133// strings134Server.prototype.registerFake = function (responseConfig, requestMatcher) {135 this.map.push({136 responseConfig: responseConfig,137 requestMatcher: requestMatcher || {}138 });139};140Server.prototype.clearFakes = function () {141 this.map = [];142};143// cb is invoked when the server emits a "listening" event144// or with any thrown error145Server.prototype.start = function (cb) {146 var self = this;147 var realCb = function () {148 if (typeof cb === "function") {149 cb.apply(null, arguments);150 }151 // if first argument is set, it's an error,152 // so throw it if a callback is not defined153 else if (arguments[0]) {154 throw arguments[0];155 }156 };157 try {158 var maxConnectionsQueueLength = 511;159 // "listening" event handler160 var handler = function () {161 self.port = self.server.address().port;162 realCb();163 };164 this.server.listen(0, "localhost", maxConnectionsQueueLength, handler);165 }166 catch (e) {167 realCb(e);168 }169};170// cb is invoked with an error if any occurs, otherwise171// with no arguments172Server.prototype.stop = function (cb) {173 var self = this;174 var realCb = function () {175 if (typeof cb === "function") {176 cb.apply(null, arguments);177 }178 else if (arguments[0]) {179 throw arguments[0];180 }181 };182 try {183 this.server.on("close", realCb);184 }185 catch (e) {186 realCb(e);187 }188 this.server.close();189};190module.exports = {191 createServer: function () {192 return new Server();193 }...

Full Screen

Full Screen

http.ts

Source:http.ts Github

copy

Full Screen

1import { Toast } from "vant"; // 提示2import axios from "axios";3import store from "../store";4let real_api = "https://test.popbadminton.com";5let venue_api = "https://test.popbadminton.com/venueapi";6let venueUploadImgUrl = "https://test.popbadminton.com/pan";7if (window.location.host.indexOf("dev") !== -1) {8 real_api = "https://dev.popbadminton.com";9} else if (window.location.host.indexOf("test") !== -1) {10 real_api = "https://test.popbadminton.com";11} else if (window.location.host.indexOf("preview") !== -1) {12 real_api = "https://preview.popbadminton.com";13 venue_api = "https://uat.popbadminton.com/venueapi";14} else if (window.location.host.indexOf("localhost") !== -1) {15 // real_api = "https://dev.popbadminton.com";16 real_api = "";17} else if (window.location.host.indexOf(":80") !== -1) {18 // real_api = " ";19 real_api = "https://test.popbadminton.com";20} else {21 venueUploadImgUrl = "https://res.popbadminton.com";22 venue_api = "https://venue.popbadminton.com";23 real_api = "https://api.popbadminton.com";24 // real_api = "https://test.popbadminton.com";25 // real_api = "https://preview.popbadminton.com";26 // real_api = "https://test.popbadminton.com";27}28localStorage.baseURL = real_api;29const venueService = axios.create({30 baseURL: venue_api,31 headers: {32 "Content-Type": "application/json-patch+json",33 },34});35const vUploadService = axios.create({36 baseURL: venueUploadImgUrl,37 headers: {38 "Content-Type": "multipart/form-data",39 },40});41const service = axios.create({42 // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url43 baseURL: real_api,44 headers: {45 "Access-Control-Allow-Headers": "openid",46 "Content-Type": "application/json;",47 // 'content-type': 'application/x-www-form-urlencoded',48 // 这些参数需要从小程序传递过来49 // token: ,50 // openid: ,51 // iv: iv,52 // encryptedData: encryptedData,53 // code: code54 },55 // withCredentials: true, // send cookies when cross-domain requests56 timeout: 5000, // request timeout57});58// 添加请求拦截器59venueService.interceptors.request.use(60 function (config: any) {61 console.log(config);62 config.headers.Authorization = sessionStorage.getItem("accessToken") || "";63 // 在发送请求之前做些什么64 // 登陆路径不刷新token65 Toast.loading({66 // message: '加载中...',67 forbidClick: true,68 });69 return config;70 },71 function (error: any) {72 // 对请求错误做些什么73 return Promise.reject(error);74 }75);76service.interceptors.request.use(77 function (config: any) {78 console.log(config);79 config.headers.token = sessionStorage.getItem("token") || "";80 config.headers.openid = sessionStorage.getItem("openid") || "";81 // 在发送请求之前做些什么82 // 登陆路径不刷新token83 Toast.loading({84 // message: '加载中...',85 forbidClick: true,86 });87 return config;88 },89 function (error: any) {90 // 对请求错误做些什么91 return Promise.reject(error);92 },93);94interface responseConfig {95 status: number;96 data: any;97}98// 添加响应拦截器99venueService.interceptors.response.use(100 function (responseConfig: responseConfig) {101 Toast.clear();102 console.log(responseConfig.status);103 console.log(responseConfig.data);104 if (responseConfig.status === 200 && responseConfig.data.success) {105 return Promise.resolve(responseConfig.data);106 } else {107 console.error(responseConfig.data, status);108 let message = "请求失败!";109 if (responseConfig.data && responseConfig.data.msg) {110 message = responseConfig.data.msg;111 }112 Toast({113 message,114 position: "middle",115 duration: 2000,116 });117 return Promise.reject(new Error(message));118 }119 },120 function (error: any) {121 Toast.clear();122 return Promise.reject(error);123 },124);125service.interceptors.response.use(126 function (responseConfig: responseConfig): any {127 Toast.clear();128 if (responseConfig.status === 200 && responseConfig.data.code === 200) {129 return Promise.resolve(responseConfig.data.data);130 } else {131 if (responseConfig.data.code === 206) {132 store.commit("setBlack", true);133 return;134 }135 console.error(responseConfig.data.code, responseConfig.status);136 let message = "请求失败!";137 if (responseConfig.data && responseConfig.data.msg) {138 message = responseConfig.data.msg;139 }140 Toast({141 message,142 position: "middle",143 duration: 2000,144 });145 return Promise.reject(new Error(message));146 }147 },148 function (error: any) {149 Toast.clear();150 return Promise.reject(error);151 },152);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const responseConfig = require('mountebank').responseConfig;2module.exports = {3 responseConfig({4 headers: {5 },6 body: {7 }8 })9};10const responseConfig = require('mountebank').responseConfig;11module.exports = {12 responseConfig({13 headers: {14 },15 body: {16 }17 })18};19const responseConfig = require('mountebank').responseConfig;20module.exports = {21 responseConfig({22 headers: {23 },24 body: {25 }26 })27};28const responseConfig = require('mountebank').responseConfig;29module.exports = {30 responseConfig({31 headers: {32 },33 body: {34 }35 })36};37const responseConfig = require('mountebank').responseConfig;38module.exports = {39 responseConfig({40 headers: {41 },42 body: {43 }44 })45};46const responseConfig = require('mountebank').responseConfig;47module.exports = {48 responseConfig({49 headers: {50 },51 body: {52 }53 })54};

Full Screen

Using AI Code Generation

copy

Full Screen

1const responseConfig = require('mountebank').responseConfig;2module.exports = {3 responseConfig({4 headers: {5 },6 body: {

Full Screen

Using AI Code Generation

copy

Full Screen

1const responseConfig = require('mountebank').responseConfig;2const imposter = {3 {4 responseConfig({5 headers: {6 },7 body: {8 }9 })10 }11};12const mb = require('mountebank').create();13mb.start().then(() => {14 return mb.post('/imposters', imposter);15});16const responseConfig = require('mountebank').responseConfig;17const imposter = {18 {19 responseConfig({20 headers: {21 },22 body: {23 }24 })25 }26};27const mb = require('mountebank').create();28mb.start().then(() => {29 return mb.post('/imposters', imposter);30});31const stub = {32 {33 equals: {34 }35 }36 responseConfig({37 headers: {38 },39 body: {40 }41 })42};43const responseConfig = require('mountebank').responseConfig;44const imposter = {45 {46 responseConfig({

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposterConfig = {2 "stubs": [{3 "responses": [{4 "is": {5 "headers": {6 },7 "body": {8 }9 }10 }]11 }]12 },13 imposterConfig2 = {14 "stubs": [{15 "responses": [{16 "is": {17 "headers": {18 },19 "body": {20 }21 }22 }]23 }]24 },25 imposterConfig3 = {26 "stubs": [{27 "responses": [{28 "is": {29 "headers": {30 },31 "body": {32 }33 }34 }]35 }]36 }37var request = require('request');38var options = {39};40var options2 = {41};42var options3 = {43};44request(options, function(error, response, body) {45 if (error) {46 console.log(error);47 } else {48 console.log(body);49 }50});51request(options2, function(error, response, body) {52 if (error) {53 console.log(error);54 } else {55 console.log(body);56 }57});58request(options3, function(error, response, body) {59 if (error) {60 console.log(error);61 } else {62 console.log(body);63 }64});65var options4 = {66 json: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var responseConfig = require('mountebank').responseConfig;2var server = require('mountebank').create();3server.post('/imposters', {4 {5 responseConfig({6 is: {7 }8 })9 }10});11server.start();12var responseConfig = require('mountebank').responseConfig;13var server = require('mountebank').create();14server.post('/imposters', {15 {16 responseConfig({17 is: {18 }19 })20 }21});22server.start();

Full Screen

Using AI Code Generation

copy

Full Screen

1const mbHelper = require('mountebank-helper');2const config = {3 {4 {5 "equals": {6 }7 }8 {9 "is": {10 "headers": {11 },12 "body": {13 }14 }15 }16 }17};18mbHelper.responseConfig(config);19const mbHelper = require('mountebank-helper');20const request = require('supertest');21const app = require('../app');22const config = {23 {24 {25 "equals": {26 }27 }28 {29 "is": {30 "headers": {31 },32 "body": {33 }34 }35 }36 }37};38describe('test', () => {39 beforeAll((done) => {40 mbHelper.responseConfig(config)41 .then(() => {42 done();43 });44 });45 afterAll((done) => {46 mbHelper.resetImposter(config.port)47 .then(() => {48 done();49 });50 });51 test('test', async () => {52 const res = await request(app)53 .post('/test')54 .send({ data: 'test' });55 expect(res.statusCode).toEqual(200);56 expect(res.body.data).toEqual('test');57 });58});59const express = require('express');60const app = express();61app.use(express.json());62app.post('/test', (req, res) => {63 res.json(req.body);64});65module.exports = app;66{

Full Screen

Using AI Code Generation

copy

Full Screen

1const responseConfig = require('mountebank').responseConfig;2const stub = {3 responseConfig({4 headers: {5 },6 body: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var responseConfig = {3 "stubs": [{4 "responses": [{5 "is": {6 "headers": {7 },8 "body": {9 }10 }11 }]12 }]13};14mb.create(responseConfig, function (error, imposter) {15 if (error) {16 console.error("Unable to create imposter: " + error.message);17 }18 console.log("Imposter created on port " + imposter.port);19});20var mb = require('mountebank');21var responseConfig = {22 "stubs": [{23 "responses": [{24 "is": {25 "headers": {26 },27 "body": {28 }29 }30 }]31 }]32};33mb.create(responseConfig, function (error, imposter) {34 if (error) {35 console.error("Unable to create imposter: " + error.message);36 }37 console.log("Imposter created on port " + imposter.port);38});39var mb = require('mountebank');40var responseConfig = {41 "stubs": [{42 "responses": [{43 "is": {44 "headers": {45 },46 "body": {47 }48 }49 }]50 }]51};52mb.create(responseConfig, function (error, imposter) {53 if (error) {54 console.error("Unable to create imposter: " + error.message);55 }56 console.log("Imposter created

Full Screen

Using AI Code Generation

copy

Full Screen

1var responseConfig = require("mountebank").responseConfig;2var imposter = {3 {4 responseConfig({5 headers: { "Content-Type": "application/json" },6 body: { success: true }7 })8 }9};10var mb = require("mountebank");11mb.create(imposter).then(function () {12 console.log("Imposter created");13});14var mb = require("mountebank");15mb.create(imposter).then(function () {16 console.log("Imposter created");17});18var mb = require("mountebank");19mb.create(imposter).then(function () {20 console.log("Imposter created");21});22var mb = require("mountebank");23mb.create(imposter).then(function () {24 console.log("Imposter created");25});26var mb = require("mountebank");27mb.create(imposter).then(function () {28 console.log("Imposter created");29});30var mb = require("mountebank");31mb.create(imposter).then(function () {32 console.log("Imposter created");33});34var mb = require("mountebank");35mb.create(imposter).then(function () {36 console.log("Imposter created");37});38var mb = require("mountebank");39mb.create(imposter).then(function () {40 console.log("Imposter created");41});42var mb = require("mountebank");43mb.create(imposter).then(function () {44 console.log("Imposter created");45});46var mb = require("mountebank");47mb.create(imposter).then(function () {48 console.log("Imposter created");49});

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var config = {3};4mb.create(config, function (error, mbServer) {5 mbServer.post('/imposters', {6 {7 {8 {9 is: {10 headers: {11 },12 }13 }14 }15 }16 }, function (error, response) {17 console.log(response.statusCode);18 });19});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run mountebank automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful