Best JavaScript code snippet using mountebank
impostersRepositoryContractTest.js
Source:impostersRepositoryContractTest.js
...181 const stub = { responses: [{ is: { key: 'value' } }] },182 imposter = { port: 1, stubs: [stub], stop: mock().returns(Promise.resolve()) };183 await repo.add(imposterize(imposter));184 await repo.del(1);185 const count = await repo.stubsFor(1).count();186 assert.strictEqual(count, 0);187 });188 });189 describe('#stopAllSync', function () {190 it('should call stop() on all imposters and empty list', async function () {191 const first = { port: 1, value: 2, stop: mock().returns(Promise.resolve()) },192 second = { port: 2, value: 3, stop: mock().returns(Promise.resolve()) };193 await repo.add(imposterize(first));194 await repo.add(imposterize(second));195 repo.stopAllSync();196 assert.ok(first.stop.wasCalled(), first.stop.message());197 assert.ok(second.stop.wasCalled(), second.stop.message());198 const imposters = await repo.all();199 assert.deepEqual(imposters, []);200 });201 });202 describe('#deleteAll', function () {203 it('should call stop() on all imposters and empty list', async function () {204 const first = { port: 1, value: 2, stop: mock().returns(Promise.resolve()) },205 second = { port: 2, value: 3, stop: mock().returns(Promise.resolve()) };206 await repo.add(imposterize(first));207 await repo.add(imposterize(second));208 await repo.deleteAll();209 assert.ok(first.stop.wasCalled(), first.stop.message());210 assert.ok(second.stop.wasCalled(), second.stop.message());211 const imposters = await repo.all();212 assert.deepEqual(imposters, []);213 });214 });215 describe('#loadAll', function () {216 it('should load an empty set if nothing previously saved', async function () {217 await repo.loadAll();218 const imposters = await repo.all();219 assert.deepStrictEqual(imposters, []);220 });221 it('should load previously saved imposters', async function () {222 if (type.name === 'inMemoryImpostersRepository') {223 // Does not persist224 return;225 }226 const options = { log: { level: 'info' } };227 // FakeLogger hangs, maybe something to do with the ScopedLogger wrapping it in imposter.js228 const logger = require('../../src/util/logger').createLogger({229 console: {230 colorize: true,231 format: '%level: %message'232 }233 });234 const protocols = require('../../src/models/protocols').loadProtocols(options, '', logger, () => true, repo);235 await repo.add(imposterize({ port: 2526, protocol: 'tcp' }));236 await repo.add(imposterize({ port: 2527, protocol: 'tcp' }));237 await repo.stopAll();238 // Validate clean state239 const imposters = await repo.all();240 assert.deepStrictEqual(imposters, []);241 await repo.loadAll(protocols);242 const loaded = await repo.all();243 const ports = loaded.map(imposter => imposter.port);244 assert.deepStrictEqual(ports, [2526, 2527]);245 await repo.stopAll();246 });247 });248 describe('#stubsFor', function () {249 describe('#count', function () {250 it('should be 0 if no stubs on the imposter', async function () {251 await repo.add(imposterize({ port: 1 }));252 const count = await repo.stubsFor(1).count();253 assert.strictEqual(0, count);254 });255 it('should provide count of all stubs on imposter added initially', async function () {256 const imposter = {257 port: 1,258 protocol: 'test',259 stubs: [260 { responses: [{ is: { field: 1 } }] },261 { responses: [{ is: { field: 2 } }] }262 ]263 };264 await repo.add(imposterize(imposter));265 const count = await repo.stubsFor(1).count();266 assert.strictEqual(2, count);267 });268 it('should all stubs added after creation', async function () {269 const imposter = {270 port: 1,271 protocol: 'test',272 stubs: [{ responses: [{ is: { field: 1 } }] }]273 };274 await repo.add(imposterize(imposter));275 await repo.stubsFor(1).add({ responses: [{ is: { field: 2 } }] });276 const count = await repo.stubsFor(1).count();277 assert.strictEqual(2, count);278 });279 });280 describe('#first', function () {281 it('should default empty array to filter function if no predicates on stub', async function () {282 const imposter = {283 port: 1,284 stubs: [{ responses: [] }]285 };286 await repo.add(imposterize(imposter));287 await repo.stubsFor(1).first(predicates => {288 assert.deepEqual(predicates, []);289 return true;290 });291 });292 it('should return default stub if no match', async function () {293 const imposter = { port: 1, protocol: 'test' };294 await repo.add(imposterize(imposter));295 const match = await repo.stubsFor(1).first(() => false);296 assert.strictEqual(match.success, false);297 const response = await match.stub.nextResponse();298 assert.deepEqual(stripFunctions(response), { is: {} });299 });300 it('should return match with index', async function () {301 const stubs = repo.stubsFor(1),302 firstStub = { predicates: [{ equals: { field: 'value' } }], responses: [{ is: 'first' }] },303 secondStub = { responses: [{ is: 'third' }, { is: 'fourth' }] },304 thirdStub = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },305 imposter = { port: 1, protocol: 'test', stubs: [firstStub, secondStub, thirdStub] };306 await repo.add(imposterize(imposter));307 const match = await stubs.first(predicates => predicates.length === 0);308 assert.strictEqual(match.success, true);309 const response = await match.stub.nextResponse();310 assert.deepEqual(stripFunctions(response), { is: 'third' });311 const index = await response.stubIndex();312 assert.strictEqual(index, 1);313 });314 it('should loop through responses on nextResponse()', async function () {315 const stub = { responses: [{ is: 'first' }, { is: 'second' }] },316 imposter = { port: 1, stubs: [stub] };317 await repo.add(imposterize(imposter));318 const match = await repo.stubsFor(1).first(() => true),319 firstResponse = await match.stub.nextResponse(),320 secondResponse = await match.stub.nextResponse(),321 thirdResponse = await match.stub.nextResponse();322 assert.deepEqual(stripFunctions(firstResponse), { is: 'first' });323 assert.deepEqual(stripFunctions(secondResponse), { is: 'second' });324 assert.deepEqual(stripFunctions(thirdResponse), { is: 'first' });325 });326 it('should handle repeat behavior on nextResponse()', async function () {327 const stub = { responses: [{ is: 'first', repeat: 2 }, { is: 'second' }] },328 imposter = { port: 1, stubs: [stub] };329 await repo.add(imposterize(imposter));330 const match = await repo.stubsFor(1).first(() => true),331 firstResponse = await match.stub.nextResponse(),332 secondResponse = await match.stub.nextResponse(),333 thirdResponse = await match.stub.nextResponse(),334 fourthResponse = await match.stub.nextResponse();335 assert.deepEqual(firstResponse.is, 'first');336 assert.deepEqual(secondResponse.is, 'first');337 assert.deepEqual(thirdResponse.is, 'second');338 assert.deepEqual(fourthResponse.is, 'first');339 });340 it('should support adding responses through addResponse()', async function () {341 const imposter = { port: 1, stubs: [{}] };342 await repo.add(imposterize(imposter));343 const match = await repo.stubsFor(1).first(() => true);344 await match.stub.addResponse({ is: { field: 1 } });345 const secondMatch = await repo.stubsFor(1).first(() => true),346 response = await secondMatch.stub.nextResponse();347 assert.deepEqual(stripFunctions(response), { is: { field: 1 } });348 });349 it('should support recording matches', async function () {350 const imposter = { port: 1, stubs: [{}] };351 await repo.add(imposterize(imposter));352 const match = await repo.stubsFor(1).first(() => true);353 await match.stub.recordMatch('REQUEST', 'RESPONSE');354 const all = await repo.stubsFor(1).toJSON({ debug: true });355 assert.strictEqual(1, all[0].matches.length);356 delete all[0].matches[0].timestamp;357 assert.deepEqual(all[0].matches, [{ request: 'REQUEST', response: 'RESPONSE' }]);358 });359 });360 describe('#toJSON', function () {361 it('should return empty array if nothing added', async function () {362 const json = await repo.stubsFor(1).toJSON();363 assert.deepEqual(json, []);364 });365 it('should return all predicates and original response order of all stubs', async function () {366 const first = {367 predicates: [{ equals: { field: 'value' } }],368 responses: [{ is: { field: 1 } }, { is: { field: 2 } }]369 },370 second = {371 responses: [{ is: { key: 'value' }, behaviors: [{ repeat: 2 }] }]372 },373 imposter = { port: 1, stubs: [first, second] };374 await repo.add(imposterize(imposter));375 const match = await repo.stubsFor(1).first(() => true);376 await match.stub.nextResponse();377 const json = await repo.stubsFor(1).toJSON();378 assert.deepEqual(json, [first, second]);379 });380 it('should not return matches if debug option not set', async function () {381 const imposter = { port: 1, stubs: [{}] };382 await repo.add(imposterize(imposter));383 const match = await repo.stubsFor(1).first(() => true);384 await match.stub.recordMatch('REQUEST', 'RESPONSE');385 const all = await repo.stubsFor(1).toJSON();386 assert.strictEqual(typeof all[0].matches, 'undefined');387 });388 });389 describe('#deleteSavedProxyResponses', function () {390 it('should remove recorded responses and stubs', async function () {391 const first = {392 predicates: [{ equals: { key: 1 } }],393 responses: [{ is: { field: 1, _proxyResponseTime: 100 } }]394 },395 second = {396 predicates: [{ equals: { key: 2 } }],397 responses: [398 { is: { field: 2, _proxyResponseTime: 100 } },399 { is: { field: 3 } }400 ]401 },402 third = {403 responses: [{ proxy: { to: 'http://test.com' } }]404 },405 imposter = { port: 1, stubs: [first, second, third] };406 await repo.add(imposterize(imposter));407 await repo.stubsFor(1).deleteSavedProxyResponses();408 const json = await repo.stubsFor(1).toJSON();409 assert.deepEqual(json, [410 {411 predicates: [{ equals: { key: 2 } }],412 responses: [{ is: { field: 3 } }]413 },414 {415 responses: [{ proxy: { to: 'http://test.com' } }]416 }417 ]);418 });419 });420 describe('#overwriteAll', function () {421 it('should overwrite entire list', async function () {422 const first = { responses: [{ is: 'first' }, { is: 'second' }] },423 second = { responses: [{ is: 'third' }, { is: 'fourth' }] },424 newStub = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },425 imposter = { port: 1, stubs: [first, second] };426 await repo.add(imposterize(imposter));427 await repo.stubsFor(1).overwriteAll([newStub]);428 const all = await repo.stubsFor(1).toJSON(),429 responses = all.map(stub => stub.responses);430 assert.deepEqual(responses, [431 [{ is: 'fifth' }, { is: 'sixth' }]432 ]);433 });434 });435 describe('#overwriteAtIndex', function () {436 it('should overwrite single stub', async function () {437 const first = { responses: [{ is: 'first' }, { is: 'second' }] },438 second = { responses: [{ is: 'third' }, { is: 'fourth' }] },439 newStub = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },440 imposter = { port: 1, stubs: [first, second] };441 await repo.add(imposterize(imposter));442 await repo.stubsFor(1).overwriteAtIndex(newStub, 1);443 const all = await repo.stubsFor(1).toJSON(),444 responses = all.map(stub => stub.responses);445 assert.deepEqual(responses, [446 [{ is: 'first' }, { is: 'second' }],447 [{ is: 'fifth' }, { is: 'sixth' }]448 ]);449 });450 it('should reject the promise if no stub at that index', async function () {451 const imposter = { port: 1 };452 await repo.add(imposterize(imposter));453 try {454 await repo.stubsFor(1).overwriteAtIndex({}, 0);455 assert.fail('Should have rejected');456 }457 catch (err) {458 assert.deepEqual(err, {459 code: 'no such resource',460 message: 'no stub at index 0'461 });462 }463 });464 });465 describe('#deleteAtIndex', function () {466 it('should delete single stub', async function () {467 const first = { responses: [{ is: 'first' }, { is: 'second' }] },468 second = { responses: [{ is: 'third' }, { is: 'fourth' }] },469 third = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },470 imposter = { port: 1, stubs: [first, second, third] };471 await repo.add(imposterize(imposter));472 await repo.stubsFor(1).deleteAtIndex(0);473 const all = await repo.stubsFor(1).toJSON(),474 responses = all.map(stub => stub.responses);475 assert.deepEqual(responses, [476 [{ is: 'third' }, { is: 'fourth' }],477 [{ is: 'fifth' }, { is: 'sixth' }]478 ]);479 });480 it('should reject the promise if no stub at that index', async function () {481 const imposter = { port: 1 };482 await repo.add(imposterize(imposter));483 try {484 await repo.stubsFor(1).deleteAtIndex(0);485 assert.fail('Should have rejected');486 }487 catch (err) {488 assert.deepEqual(err, {489 code: 'no such resource',490 message: 'no stub at index 0'491 });492 }493 });494 });495 describe('#insertAtIndex', function () {496 it('should add single stub at given index', async function () {497 const first = { responses: [{ is: 'first' }, { is: 'second' }] },498 second = { responses: [{ is: 'third' }, { is: 'fourth' }] },499 insertedStub = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },500 imposter = { port: 1, stubs: [first, second] };501 await repo.add(imposterize(imposter));502 await repo.stubsFor(1).insertAtIndex(insertedStub, 0);503 const all = await repo.stubsFor(1).toJSON(),504 responses = all.map(stub => stub.responses);505 assert.deepEqual(responses, [506 [{ is: 'fifth' }, { is: 'sixth' }],507 [{ is: 'first' }, { is: 'second' }],508 [{ is: 'third' }, { is: 'fourth' }]509 ]);510 });511 });512 describe('#addRequest', function () {513 it('should save request with timestamp', async function () {514 const imposter = { port: 1 };515 await repo.add(imposterize(imposter));516 await repo.stubsFor(1).addRequest({ field: 'value' });517 const requests = await repo.stubsFor(1).loadRequests();518 assert.deepEqual(requests, [{ field: 'value', timestamp: requests[0].timestamp }]);519 const delta = new Date() - Date.parse(requests[0].timestamp);520 assert.ok(delta < 1000);521 });522 });523 describe('#deleteSavedRequests', function () {524 it('should clear the requests list', async function () {525 const imposter = { port: 1 };526 await repo.add(imposterize(imposter));527 await repo.stubsFor(1).addRequest({ field: 'value' });528 const requests = await repo.stubsFor(1).loadRequests();529 assert.deepEqual(requests, [{ field: 'value', timestamp: requests[0].timestamp }]);530 await repo.stubsFor(1).deleteSavedRequests();531 const secondRequests = await repo.stubsFor(1).loadRequests();532 assert.deepEqual(secondRequests, []);533 });534 });535 describe('#loadRequests', function () {536 it('should return requests in order without losing any', async function () {537 // Simulate enough rapid load to add two with the same millisecond timestamp538 // The filesystemBackedImpostersRepository has to add some metadata to ensure539 // we capture both if they occur at the same millisecond.540 const stubs = repo.stubsFor(1);541 await stubs.addRequest({ value: 1 });542 await stubs.addRequest({ value: 2 });543 await stubs.addRequest({ value: 3 });544 await stubs.addRequest({ value: 4 });545 await stubs.addRequest({ value: 5 });546 await stubs.addRequest({ value: 6 });547 await stubs.addRequest({ value: 7 });548 await stubs.addRequest({ value: 8 });549 await stubs.addRequest({ value: 9 });550 await stubs.addRequest({ value: 10 });551 const requests = await stubs.loadRequests(),552 values = requests.map(request => request.value);553 assert.deepEqual(values, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);554 });...
imposterController.js
Source:imposterController.js
...60 */61 function resetProxies (request, response) {62 const options = { replayable: false, removeProxies: false };63 return imposters.get(request.params.id).then(imposter => {64 return imposters.stubsFor(request.params.id).deleteSavedProxyResponses()65 .then(() => imposter.toJSON(options));66 }).then(json => {67 response.format({68 json: () => { response.send(json); },69 html: () => {70 if (request.headers['x-requested-with']) {71 response.render('_imposter', { imposter: json });72 }73 else {74 response.render('imposter', { imposter: json });75 }76 }77 });78 });79 }80 /**81 * Corresponds to DELETE /imposters/:id/savedRequests82 * Removes all saved requests83 * @memberOf module:controllers/imposterController#84 * @param {Object} request - the HTTP request85 * @param {Object} response - the HTTP response86 * @returns {Object} A promise for testing87 */88 function resetRequests (request, response) {89 return imposters.get(request.params.id).then(imposter => {90 return imposters.stubsFor(request.params.id).deleteSavedRequests()91 .then(() => imposter.toJSON());92 }).then(json => {93 response.format({94 json: () => { response.send(json); },95 html: () => {96 if (request.headers['x-requested-with']) {97 response.render('_imposter', { imposter: json });98 }99 else {100 response.render('imposter', { imposter: json });101 }102 }103 });104 });105 }106 /**107 * The function responding to DELETE /imposters/:id108 * @memberOf module:controllers/imposterController#109 * @param {Object} request - the HTTP request110 * @param {Object} response - the HTTP response111 * @returns {Object} A promise for testing112 */113 function del (request, response) {114 const Q = require('q'),115 url = require('url'),116 query = url.parse(request.url, true).query,117 options = {118 replayable: queryBoolean(query, 'replayable'),119 removeProxies: queryBoolean(query, 'removeProxies')120 };121 return imposters.get(request.params.id).then(imposter => {122 if (imposter) {123 return imposter.toJSON(options).then(json => {124 return imposters.del(request.params.id).then(() => {125 response.send(json);126 });127 });128 }129 else {130 response.send({});131 return Q(true);132 }133 });134 }135 /**136 * The function responding to POST /imposters/:id/_requests137 * This is what protocol implementations call to send the JSON request138 * structure to mountebank, which responds with the JSON response structure139 * @memberOf module:controllers/imposterController#140 * @param {Object} request - the HTTP request141 * @param {Object} response - the HTTP response142 * @returns {Object} - the promise143 */144 function postRequest (request, response) {145 return imposters.get(request.params.id)146 .then(imposter => imposter.getResponseFor(request.body.request))147 .then(jsonResponse => response.send(jsonResponse));148 }149 /**150 * The function responding to POST /imposters/:id/_requests/:proxyResolutionKey151 * This is what protocol implementations call after proxying a request so152 * mountebank can record the response and add behaviors to153 * @memberOf module:controllers/imposterController#154 * @param {Object} request - the HTTP request155 * @param {Object} response - the HTTP response156 * @returns {Object} - the promise157 */158 function postProxyResponse (request, response) {159 const proxyResolutionKey = request.params.proxyResolutionKey,160 proxyResponse = request.body.proxyResponse;161 return imposters.get(request.params.id).then(imposter =>162 imposter.getProxyResponseFor(proxyResponse, proxyResolutionKey)163 ).then(json => response.send(json));164 }165 function validateStubs (imposter, newStubs) {166 const errors = [],167 Q = require('q');168 if (!helpers.defined(newStubs)) {169 errors.push(exceptions.ValidationError("'stubs' is a required field"));170 }171 else if (!require('util').isArray(newStubs)) {172 errors.push(exceptions.ValidationError("'stubs' must be an array"));173 }174 if (errors.length > 0) {175 return Q({ isValid: false, errors });176 }177 return imposter.toJSON().then(request => {178 const compatibility = require('../models/compatibility'),179 Protocol = protocols[request.protocol],180 validator = require('../models/dryRunValidator').create({181 testRequest: Protocol.testRequest,182 testProxyResponse: Protocol.testProxyResponse,183 additionalValidation: Protocol.validate,184 allowInjection: allowInjection185 });186 request.stubs = newStubs;187 compatibility.upcast(request);188 return validator.validate(request, logger);189 });190 }191 function respondWithValidationErrors (response, validationErrors, statusCode = 400) {192 logger.error(`error changing stubs: ${JSON.stringify(exceptions.details(validationErrors))}`);193 response.statusCode = statusCode;194 response.send({ errors: validationErrors });195 return require('q')();196 }197 /**198 * The function responding to PUT /imposters/:id/stubs199 * Overwrites the stubs list without restarting the imposter200 * @memberOf module:controllers/imposterController#201 * @param {Object} request - the HTTP request202 * @param {Object} response - the HTTP response203 * @returns {Object} - promise for testing204 */205 function putStubs (request, response) {206 return imposters.get(request.params.id).then(imposter => {207 const stubs = imposters.stubsFor(request.params.id),208 newStubs = request.body.stubs;209 return validateStubs(imposter, newStubs).then(result => {210 if (!result.isValid) {211 return respondWithValidationErrors(response, result.errors);212 }213 return stubs.overwriteAll(newStubs).then(() => {214 return imposter.toJSON().then(json => response.send(json));215 });216 });217 });218 }219 function validateStubIndex (stubs, index) {220 return stubs.toJSON().then(allStubs => {221 const errors = [];222 if (typeof allStubs[index] === 'undefined') {223 errors.push(exceptions.ValidationError("'stubIndex' must be a valid integer, representing the array index position of the stub to replace"));224 }225 return { isValid: errors.length === 0, errors };226 });227 }228 /**229 * The function responding to PUT /imposters/:id/stubs/:stubIndex230 * Overwrites a single stub without restarting the imposter231 * @memberOf module:controllers/imposterController#232 * @param {Object} request - the HTTP request233 * @param {Object} response - the HTTP response234 * @returns {Object} - promise for testing235 */236 function putStub (request, response) {237 return imposters.get(request.params.id).then(imposter => {238 const stubs = imposters.stubsFor(request.params.id);239 return validateStubIndex(stubs, request.params.stubIndex).then(validation => {240 if (!validation.isValid) {241 return respondWithValidationErrors(response, validation.errors, 404);242 }243 const newStub = request.body;244 return validateStubs(imposter, [newStub]).then(result => {245 if (!result.isValid) {246 return respondWithValidationErrors(response, result.errors);247 }248 return stubs.overwriteAtIndex(newStub, request.params.stubIndex)249 .then(() => imposter.toJSON())250 .then(json => response.send(json));251 });252 });253 });254 }255 function validateNewStubIndex (index, allStubs) {256 const errors = [];257 if (typeof index !== 'number' || index < 0 || index > allStubs.length) {258 errors.push(exceptions.ValidationError("'index' must be between 0 and the length of the stubs array"));259 }260 return { isValid: errors.length === 0, errors };261 }262 /**263 * The function responding to POST /imposters/:port/stubs264 * Creates a single stub without restarting the imposter265 * @memberOf module:controllers/imposterController#266 * @param {Object} request - the HTTP request267 * @param {Object} response - the HTTP response268 * @returns {Object} - promise for testing269 */270 function postStub (request, response) {271 return imposters.get(request.params.id).then(imposter => {272 const stubs = imposters.stubsFor(request.params.id);273 return stubs.toJSON().then(allStubs => {274 const newStub = request.body.stub,275 index = typeof request.body.index === 'undefined' ? allStubs.length : request.body.index,276 indexValidation = validateNewStubIndex(index, allStubs);277 logger.error(JSON.stringify(indexValidation));278 if (!indexValidation.isValid) {279 return respondWithValidationErrors(response, indexValidation.errors);280 }281 return validateStubs(imposter, [newStub]).then(result => {282 if (!result.isValid) {283 return respondWithValidationErrors(response, result.errors);284 }285 return stubs.insertAtIndex(newStub, index).then(() => {286 return imposter.toJSON().then(json => response.send(json));287 });288 });289 });290 });291 }292 /**293 * The function responding to DELETE /imposters/:port/stubs/:stubIndex294 * Removes a single stub without restarting the imposter295 * @memberOf module:controllers/imposterController#296 * @param {Object} request - the HTTP request297 * @param {Object} response - the HTTP response298 * @returns {Object} - promise for testing299 */300 function deleteStub (request, response) {301 return imposters.get(request.params.id).then(imposter => {302 const stubs = imposters.stubsFor(request.params.id);303 return validateStubIndex(stubs, request.params.stubIndex).then(validation => {304 if (!validation.isValid) {305 return respondWithValidationErrors(response, validation.errors, 404);306 }307 return stubs.deleteAtIndex(request.params.stubIndex).then(() => {308 return imposter.toJSON().then(json => response.send(json));309 });310 });311 });312 }313 return {314 get,315 del,316 resetProxies,...
Using AI Code Generation
1var mb = require('mountebank');2var imposters = {3 stubs: [{4 predicates: [{5 equals: {6 }7 }],8 responses: [{9 is: {10 headers: {11 },12 body: {13 }14 }15 }]16 }]17};18mb.create(imposters, function (error, response) {19 console.log(response);20});21var mb = require('mountebank');22var imposters = {23 stubs: [{24 predicates: [{25 equals: {26 }27 }],28 responses: [{29 is: {30 headers: {31 },32 body: {33 }34 }35 }]36 }]37};38describe("mountebank", function () {39 it("should create imposters", function (done) {40 var mock = sinon.mock(mb);41 mock.expects("create").once().withArgs(imposters).yields(null, {42 });43 mb.create(imposters, function (error, response) {44 console.log(response);45 mock.verify();46 done();47 });48 });49});50var proxyquire = require('proxyquire');51var proxyquire = require('proxyquire');52var mb = proxyquire('mountebank', {53 'mountebank': sinon.stub()54});
Using AI Code Generation
1 {2 {3 equals: {4 }5 }6 {7 is: {8 headers: {9 },10 body: {11 }12 }13 }14 }15];16var imposter = {17};18var mb = require('mountebank');19mb.create({ port: 2525 }, function (error, mbServer) {20 if (error) {21 console.error(error);22 }23 else {24 mbServer.stubsFor(imposter, function (error, imposter) {25 if (error) {26 console.error(error);27 }28 else {29 console.log(imposter.port);30 }31 });32 }33});34var mb = require('mountebank');35mb.create({ port: 2525 }, function (error, mbServer) {36 if (error) {37 console.error(error);38 }39 else {40 mbServer.stubsFor(imposter, function (error, imposter) {41 if (error) {42 console.error(error);43 }44 else {45 console.log(imposter.port);46 }47 });48 }49});50var mb = require('mountebank');51mb.create({ port: 2525 }, function (error, mbServer) {52 if (error) {53 console.error(error);54 }55 else {56 mbServer.stubsFor(imposter, function (error, imposter) {57 if (error) {58 console.error(error);59 }60 else {61 console.log(imposter.port);62 }63 });64 }65});66var mb = require('mountebank');67mb.create({ port: 2525 }, function (error, mbServer) {68 if (error) {69 console.error(error);70 }71 else {72 mbServer.stubsFor(imposter, function (error, imposter) {
Using AI Code Generation
1var mb = require('mountebank');2mb.create({port:2525, pidfile: 'mb.pid', logfile: 'mb.log'}, function (error, imposter) {3 if (error) {4 console.log('error creating imposter: ', error);5 }6 else {7 console.log('imposter created on port ', imposter.port);8 imposter.stubsFor({9 {10 {11 equals: {12 }13 }14 {15 is: {16 headers: {17 },18 body: JSON.stringify({message: 'Hello World'})19 }20 }21 }22 }, function (error, stubs) {23 if (error) {24 console.log('error creating stubs: ', error);25 }26 else {27 console.log('stubs created: ', stubs);28 }29 });30 }31});32var mb = require('mountebank');33mb.create({port:2525, pidfile: 'mb.pid', logfile: 'mb.log'}, function (error, imposter) {34 if (error) {35 console.log('error creating imposter: ', error);36 }37 else {38 console.log('imposter created on port ', imposter.port);39 imposter.stubsFor({40 {41 {42 equals: {43 }44 }45 {46 is: {47 headers: {48 },49 body: JSON.stringify({message: 'Hello World'})50 }51 }52 }53 }, function (error, stubs) {54 if (error) {55 console.log('error creating stubs: ', error);56 }57 else {58 console.log('stubs created: ', stubs);59 }60 });61 }62});
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const protocol = 'http';4const host = 'localhost';5const stub = {6 {7 is: {8 }9 }10};11 {12 matches: {13 }14 }15];16 {17 }18];19const imposter = {20};21const imposterUrl = `${url}/imposters`;22mb.create(url, imposter)23 .then(() => {24 console.log('Imposter created');25 return mb.stubsFor(imposterUrl, stubs);26 })27 .then(() => {28 console.log('Stubs created');29 return mb.get(url);30 })31 .then(response => {32 console.log('Imposter retrieved');33 console.log(JSON.stringify(response.body, null, 2));34 })35 .catch(error => console.log(error));36const mb = require('mountebank');37const port = 2525;38const protocol = 'http';39const host = 'localhost';40const stub = {41 {42 is: {43 }44 }45};46 {47 matches: {48 }49 }50];51 {52 }53];54const imposter = {55};56const imposterUrl = `${url}/imposters`;57describe('Imposter', () => {58 beforeAll(async () => {59 await mb.create(url, imposter);60 });61 afterAll(async () => {62 await mb.del(url);63 });64 it('should create an imposter', async () => {65 const response = await mb.get(url);66 expect(response.body.imposters.length).toEqual(1);67 expect(response.body.imposters[0].port).toEqual(imposter.port);68 });69 it('should create stubs', async ()
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var imposters = { imposters: [4 { protocol: 'http',5 { responses: [6 { is: { body: 'Hello world!' } }7 }8 }9};10mb.create(port, imposters, function () {11 console.log('Imposter created');12});13var mb = require('mountebank');14var port = 2525;15var imposters = { imposters: [16 { protocol: 'http',17 { responses: [18 { is: { body: 'Hello world!' } }19 }20 }21};22mb.create(port, imposters, function () {23 console.log('Imposter created');24});25var mb = require('mountebank');26var port = 2525;27var imposters = { imposters: [28 { protocol: 'http',29 { responses: [30 { is: { body: 'Hello world!' } }31 }32 }33};34mb.create(port, imposters, function () {35 console.log('Imposter created');36});37var mb = require('mountebank');38var port = 2525;39var imposters = { imposters: [40 { protocol: 'http',41 { responses: [42 { is: { body: 'Hello world!' } }43 }44 }45};46mb.create(port, imposters, function () {47 console.log('Imposter created');48});
Using AI Code Generation
1const mb = require('mountebank');2const fs = require('fs');3const path = require('path');4const request = require('request');5const port = 2525;6const imposterPort = 2526;7const imposter = {8 "stubs": [{9 "responses": [{10 "is": {11 "headers": {12 },13 }14 }]15 }]16};17mb.create(port, imposter).then(() => {18 console.log('Imposter created!');19 console.log(`response from imposter: ${body}`);20 mb.stop(port).then(() => {21 console.log('Imposter stopped!');22 });23 });24});25* **Shubham Saini** - *Initial work* - [shubham-sns](
Using AI Code Generation
1var mb = require('mountebank');2var request = require('request');3var assert = require('assert');4describe('Test', function () {5 it('should return 200', function (done) {6 var stub = {7 responses: [{8 is: {9 }10 }]11 };12 mb.stubFor({ port: 4545, stub: stub }, function (error, response) {13 assert.equal(response.statusCode, 200);14 done();15 });16 });17 });18});19{20 "scripts": {21 },22 "devDependencies": {23 }24}
Using AI Code Generation
1const mb = require('mountebank-client');2const port = 2525;3const mbClient = mb.create(port);4const imposters = require('./imposters.json');5mbClient.stubFor(imposters);6{7 {8 {9 "is": {10 "headers": {11 },12 "body": {13 }14 }15 }16 }17}
Using AI Code Generation
1var mb = require('mountebank');2var assert = require('assert');3var config = require('./config');4var request = require('request');5describe('Test', function() {6 this.timeout(10000);7 before(function(done) {8 mb.create(config.mbConfig, done);9 });10 after(function(done) {11 mb.stop(done);12 });13 it('should return 200', function(done) {14 var stub = {15 predicates: [{16 equals: {17 }18 }],19 responses: [{20 is: {21 }22 }]23 };24 mb.stubFor(stub, function(error) {25 assert.ifError(error);26 assert.ifError(error);27 assert.equal(response.statusCode, 200);28 done();29 });30 });31 });32});33var config = {34 mbConfig: {35 }36};37module.exports = config;
Using AI Code Generation
1const mb = require('mountebank');2const config = require('./config');3const logger = require('./logger');4const config = require('./config');5const stubs = require('./stubs');6const mbHost = config.mountebank.host;7const mbPort = config.mountebank.port;8const imposterPort = config.mountebank.imposterPort;9const mbClient = mb.createClient({10});11const imposter = {12};13const imposterUrl = `${mbUrl}/imposters/${imposterPort}`;14const createImposter = () => {15 return mbClient.post('/imposters', imposter);16};17const deleteImposter = () => {18 return mbClient.del(`/imposters/${imposterPort}`);19};20const getImposter = () => {21 return mbClient.get(`/imposters/${imposterPort}`);22};23const resetImposter = () => {24 return mbClient.del(`/imposters/${imposterPort}/requests`);25};26const getRequests = () => {27 return mbClient.get(`/imposters/${imposterPort}/requests`);28};29const getRequestsFor = (path) => {30 return mbClient.get(`/imposters/${imposterPort}/requests?path=${path}`);31};32const getRequestsForMethod = (method) => {33 return mbClient.get(`/imposters/${imposterPort}/requests?method=${method}`);34};35const getRequestsForPathAndMethod = (path, method) => {36 return mbClient.get(`/imposters/${imposterPort}/requests?path=${path}&method=${method}`);37};38const getRequestsForPathAndQuery = (path, query) => {39 return mbClient.get(`/imposters/${imposterPort}/requests?path=${path}&query=${query}`);40};41const getRequestsForPathAndBody = (path, body) => {42 return mbClient.get(`/imposters/${imposterPort}/requests?path=${path}&body=${body}`);43};44const getRequestsForPathAndMethodAndQuery = (path, method, query) => {45 return mbClient.get(`/imposters/${imposterPort}/requests?path=${path}&method=${method}&query=${query}`);46};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!