How to use getResponseFrom method in mountebank

Best JavaScript code snippet using mountebank

responseResolverTest.js

Source:responseResolverTest.js Github

copy

Full Screen

...50 resolver = ResponseResolver.create(stubs, proxy),51 logger = Logger.create();52 // Call through the stubRepository to have it add the setMetadata function53 await stubs.add({ responses: [{ proxy: { to: 'where' } }] });54 const responseConfig = await getResponseFrom(stubs),55 response = await resolver.resolve(responseConfig, 'request', logger, {});56 assert.strictEqual(response.key, 'value');57 assert.ok(proxy.to.wasCalledWith('where', 'request', {58 to: 'where',59 mode: 'proxyOnce'60 }), proxy.to.message());61 });62 it('should resolve "proxy" by returning proxy configuration for out of process resolution', async function () {63 const stubs = createStubsRepository(),64 resolver = ResponseResolver.create(stubs, null, 'CALLBACK URL'),65 logger = Logger.create();66 // Call through the stubRepository to have it add the setMetadata function67 await stubs.add({ responses: [{ proxy: { to: 'where' } }] });68 const responseConfig = await getResponseFrom(stubs),69 response = await resolver.resolve(responseConfig, 'request', logger, {});70 assert.deepEqual(response, {71 proxy: { to: 'where', mode: 'proxyOnce' },72 request: 'request',73 callbackURL: 'CALLBACK URL/0'74 });75 });76 it('should default to "proxyOnce" mode', async function () {77 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },78 stubs = createStubsRepository(),79 resolver = ResponseResolver.create(stubs, proxy),80 logger = Logger.create();81 // Call through the stubRepository to have it add the setMetadata function82 await stubs.add({ responses: [{ proxy: { to: 'where' } }] });83 const responseConfig = await getResponseFrom(stubs);84 await resolver.resolve(responseConfig, 'request', logger, {});85 assert.strictEqual(responseConfig.proxy.mode, 'proxyOnce');86 });87 it('should change unrecognized mode to "proxyOnce" mode', async function () {88 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },89 stubs = createStubsRepository(),90 resolver = ResponseResolver.create(stubs, proxy),91 logger = Logger.create();92 // Call through the stubRepository to have it add the setMetadata function93 await stubs.add({ responses: [{ proxy: { to: 'where', mode: 'unrecognized' } }] });94 const responseConfig = await getResponseFrom(stubs);95 await resolver.resolve(responseConfig, 'request', logger, {});96 assert.strictEqual(responseConfig.proxy.mode, 'proxyOnce');97 });98 it('should resolve proxy in proxyOnce mode by adding a new "is" stub to the front of the list', async function () {99 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },100 stubs = createStubsRepository(),101 resolver = ResponseResolver.create(stubs, proxy),102 logger = Logger.create();103 await stubs.add({ responses: [], predicates: [{ equals: { ignore: 'true' } }] });104 await stubs.add({ responses: [{ proxy: { to: 'where' } }] });105 const responseConfig = await getResponseFrom(stubs),106 response = await resolver.resolve(responseConfig, {}, logger, {}),107 all = await stubs.toJSON(),108 stubResponses = all.map(stub => proxyResponses(stub.responses));109 assert.strictEqual(response.key, 'value');110 assert.deepEqual(stubResponses, [111 [],112 [{ is: { key: 'value' } }],113 [{ proxy: { to: 'where' } }]114 ]);115 });116 it('should support adding wait behavior to newly created stub for in process imposters', async function () {117 const proxy = { to: mock().returns(delay(100).then(() => Promise.resolve({ data: 'value' }))) },118 stubs = createStubsRepository(),119 resolver = ResponseResolver.create(stubs, proxy),120 logger = Logger.create(),121 request = {};122 await stubs.add({ responses: [{ proxy: { to: 'where', addWaitBehavior: true } }] });123 const responseConfig = await getResponseFrom(stubs);124 await resolver.resolve(responseConfig, request, logger, {});125 const all = await stubs.toJSON(),126 stubResponses = all.map(stub => stub.responses),127 wait = stubResponses[0][0].is._proxyResponseTime;128 assert.ok(wait > 90); // allow some variability129 assert.deepEqual(stubResponses, [130 [{ is: { data: 'value', _proxyResponseTime: wait }, behaviors: [{ wait: wait }] }],131 [{ proxy: { to: 'where', addWaitBehavior: true } }]132 ]);133 });134 it('should support adding wait behavior to newly created response in proxyAlways mode', async function () {135 let call = 0;136 async function proxyReturn () {137 await delay(100);138 call += 1;139 return { data: call };140 }141 const proxy = { to: proxyReturn },142 stubs = createStubsRepository(),143 resolver = ResponseResolver.create(stubs, proxy),144 logger = Logger.create(),145 request = {};146 await stubs.add({ responses: [{ proxy: { to: 'where', mode: 'proxyAlways', addWaitBehavior: true } }] });147 const responseConfig = await getResponseFrom(stubs);148 // First call adds the stub, second call adds a response149 await resolver.resolve(responseConfig, request, logger, {});150 await resolver.resolve(responseConfig, request, logger, {});151 const all = await stubs.toJSON(),152 stubResponses = all.map(stub => stub.responses),153 firstWait = stubResponses[1][0].is._proxyResponseTime,154 secondWait = stubResponses[1][1].is._proxyResponseTime;155 assert.deepEqual(stubResponses, [156 [{ proxy: { to: 'where', mode: 'proxyAlways', addWaitBehavior: true } }],157 [158 { is: { data: 1, _proxyResponseTime: firstWait }, behaviors: [{ wait: firstWait }] },159 { is: { data: 2, _proxyResponseTime: secondWait }, behaviors: [{ wait: secondWait }] }160 ]161 ]);162 });163 it('should run behaviors on proxy response before recording it', async function () {164 const decorateFunc = (request, response) => { response.data += '-DECORATED'; };165 const proxy = { to: mock().returns(Promise.resolve({ data: 'RESPONSE' })) },166 stubs = createStubsRepository(),167 resolver = ResponseResolver.create(stubs, proxy),168 logger = Logger.create(),169 response = {170 proxy: { to: 'where' },171 behaviors: [{ decorate: decorateFunc.toString() }]172 },173 request = {};174 await stubs.add({ responses: [response] });175 const responseConfig = await getResponseFrom(stubs);176 await resolver.resolve(responseConfig, request, logger, {});177 const all = await stubs.toJSON(),178 stubResponses = all.map(stub => proxyResponses(stub.responses));179 assert.deepEqual(stubResponses, [180 [{ is: { data: 'RESPONSE-DECORATED' } }],181 [{ proxy: { to: 'where' }, behaviors: [{ decorate: decorateFunc.toString() }] }]182 ]);183 });184 it('should support adding decorate behavior to newly created stub', async function () {185 const decorateFunc = '(request, response) => {}';186 const proxy = { to: mock().returns(Promise.resolve({ data: 'value' })) },187 stubs = createStubsRepository(),188 resolver = ResponseResolver.create(stubs, proxy),189 logger = Logger.create(),190 request = {};191 await stubs.add({ responses: [{ proxy: { to: 'where', addDecorateBehavior: decorateFunc } }] });192 const responseConfig = await getResponseFrom(stubs);193 await resolver.resolve(responseConfig, request, logger, {});194 const all = await stubs.toJSON(),195 stubResponses = all.map(stub => proxyResponses(stub.responses));196 assert.deepEqual(stubResponses, [197 [{ is: { data: 'value' }, behaviors: [{ decorate: decorateFunc }] }],198 [{ proxy: { to: 'where', addDecorateBehavior: decorateFunc } }]199 ]);200 });201 it('should support adding decorate behavior to newly created response in proxyAlways mode', async function () {202 const decorateFunc = '(request, response) => {}';203 const proxy = { to: mock().returns(Promise.resolve({ data: 'value' })) },204 stubs = createStubsRepository(),205 resolver = ResponseResolver.create(stubs, proxy),206 logger = Logger.create(),207 request = {};208 await stubs.add({ responses: [{ proxy: { to: 'where', mode: 'proxyAlways', addDecorateBehavior: decorateFunc } }] });209 const responseConfig = await getResponseFrom(stubs);210 // First call adds the stub, second call adds a response211 await resolver.resolve(responseConfig, request, logger, {});212 await resolver.resolve(responseConfig, request, logger, stubs);213 const all = await stubs.toJSON(),214 stubResponses = all.map(stub => proxyResponses(stub.responses));215 assert.deepEqual(stubResponses, [216 [{ proxy: { to: 'where', mode: 'proxyAlways', addDecorateBehavior: decorateFunc } }],217 [218 { is: { data: 'value' }, behaviors: [{ decorate: decorateFunc }] },219 { is: { data: 'value' }, behaviors: [{ decorate: decorateFunc }] }220 ]221 ]);222 });223 it('should resolve "proxy" and remember full objects as "deepEquals" predicates', async function () {224 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },225 stubs = createStubsRepository(),226 resolver = ResponseResolver.create(stubs, proxy),227 logger = Logger.create(),228 response = {229 proxy: {230 to: 'where',231 predicateGenerators: [{ matches: { key: true } }]232 }233 },234 request = { key: { nested: { first: 'one', second: 'two' }, third: 'three' } };235 await stubs.add({ responses: [response] });236 const responseConfig = await getResponseFrom(stubs);237 await resolver.resolve(responseConfig, request, logger, {});238 const stubList = await stubListFor(stubs);239 assert.deepEqual(stubList, [240 {241 predicates: [{242 deepEquals: {243 key: {244 nested: { first: 'one', second: 'two' },245 third: 'three'246 }247 }248 }],249 responses: [{ is: { key: 'value' } }]250 },251 {252 responses: [{253 proxy: { to: 'where', predicateGenerators: [{ matches: { key: true } }] }254 }]255 }256 ]);257 });258 it('should resolve "proxy" and remember nested keys as "equals" predicates', async function () {259 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },260 stubs = createStubsRepository(),261 resolver = ResponseResolver.create(stubs, proxy),262 logger = Logger.create(),263 response = {264 proxy: {265 to: 'where',266 mode: 'proxyOnce',267 predicateGenerators: [{ matches: { key: { nested: { first: true } } } }]268 }269 },270 request = { key: { nested: { first: 'one', second: 'two' }, third: 'three' } };271 await stubs.add({ responses: [response] });272 const responseConfig = await getResponseFrom(stubs);273 await resolver.resolve(responseConfig, request, logger, {});274 const stubList = await stubListFor(stubs);275 assert.deepEqual(stubList, [276 {277 predicates: [{ equals: { key: { nested: { first: 'one' } } } }],278 responses: [{ is: { key: 'value' } }]279 },280 {281 responses: [{282 proxy: {283 to: 'where',284 mode: 'proxyOnce',285 predicateGenerators: [{ matches: { key: { nested: { first: true } } } }]286 }287 }]288 }289 ]);290 });291 it('should add predicate parameters from predicateGenerators', async function () {292 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },293 stubs = createStubsRepository(),294 resolver = ResponseResolver.create(stubs, proxy),295 logger = Logger.create(),296 response = {297 proxy: {298 to: 'where',299 mode: 'proxyOnce',300 predicateGenerators: [{301 matches: { key: true },302 caseSensitive: true,303 except: 'xxx'304 }]305 }306 },307 request = { key: 'Test' };308 await stubs.add({ responses: [response] });309 const responseConfig = await getResponseFrom(stubs);310 await resolver.resolve(responseConfig, request, logger, {});311 const stubList = await stubListFor(stubs);312 assert.deepEqual(stubList, [313 {314 predicates: [{315 deepEquals: { key: 'Test' },316 caseSensitive: true,317 except: 'xxx'318 }],319 responses: [{ is: { key: 'value' } }]320 },321 {322 responses: [response]323 }324 ]);325 });326 it('should choose predicate operator from predicateGenerators', async function () {327 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },328 stubs = createStubsRepository(),329 resolver = ResponseResolver.create(stubs, proxy),330 logger = Logger.create(),331 response = {332 proxy: {333 to: 'where',334 mode: 'proxyOnce',335 predicateGenerators: [{336 matches: { key: true },337 predicateOperator: 'contains'338 }]339 }340 },341 request = { key: 'Test' };342 await stubs.add({ responses: [response] });343 const responseConfig = await getResponseFrom(stubs);344 await resolver.resolve(responseConfig, request, logger, {});345 const stubList = await stubListFor(stubs);346 assert.deepEqual(stubList, [347 {348 predicates: [{349 contains: { key: 'Test' }350 }],351 responses: [{ is: { key: 'value' } }]352 },353 {354 responses: [response]355 }356 ]);357 });358 it('should format exists matcher from predicateOperator', async function () {359 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },360 stubs = createStubsRepository(),361 resolver = ResponseResolver.create(stubs, proxy),362 logger = Logger.create(),363 response = {364 proxy: {365 to: 'where',366 mode: 'proxyOnce',367 predicateGenerators: [{368 matches: { key: true },369 predicateOperator: 'exists'370 }]371 }372 },373 request = { key: 'Test' };374 await stubs.add({ responses: [response] });375 const responseConfig = await getResponseFrom(stubs);376 await resolver.resolve(responseConfig, request, logger, {});377 const stubList = await stubListFor(stubs);378 assert.deepEqual(stubList, [379 {380 predicates: [{381 exists: { key: true }382 }],383 responses: [{ is: { key: 'value' } }]384 },385 {386 responses: [response]387 }388 ]);389 });390 it('should format exists matcher from predicateOperator with nested match', async function () {391 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },392 stubs = createStubsRepository(),393 resolver = ResponseResolver.create(stubs, proxy),394 logger = Logger.create(),395 response = {396 proxy: {397 to: 'where',398 mode: 'proxyOnce',399 predicateGenerators: [{400 matches: { key: { nested: true } },401 predicateOperator: 'exists'402 }]403 }404 },405 request = { key: { nested: 'Test' } };406 await stubs.add({ responses: [response] });407 const responseConfig = await getResponseFrom(stubs);408 await resolver.resolve(responseConfig, request, logger, {});409 const stubList = await stubListFor(stubs);410 assert.deepEqual(stubList, [411 {412 predicates: [{413 exists: { key: { nested: true } }414 }],415 responses: [{ is: { key: 'value' } }]416 },417 {418 responses: [response]419 }420 ]);421 });422 it('should support "inject" predicateGenerators', async function () {423 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },424 stubs = createStubsRepository(),425 resolver = ResponseResolver.create(stubs, proxy),426 logger = Logger.create(),427 response = {428 proxy: {429 to: 'where',430 mode: 'proxyOnce',431 predicateGenerators: [{432 inject: 'function(config) { return [{ deepEquals: config.request, caseSensitive: true }, { not: { equals: { foo: "bar" }}}]; }'433 }]434 }435 },436 request = { key: 'Test' };437 await stubs.add({ responses: [response] });438 const responseConfig = await getResponseFrom(stubs);439 await resolver.resolve(responseConfig, request, logger, {});440 const stubList = await stubListFor(stubs);441 assert.deepEqual(stubList, [442 {443 predicates: [{444 deepEquals: { key: 'Test' },445 caseSensitive: true446 }, {447 not: {448 equals: { foo: 'bar' }449 }450 }],451 responses: [{ is: { key: 'value' } }]452 },453 {454 responses: [response]455 }456 ]);457 });458 it('should log "inject" predicateGenerator exceptions', async function () {459 const errorsLogged = [],460 proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },461 stubs = createStubsRepository(),462 resolver = ResponseResolver.create(stubs, proxy),463 logger = Logger.create(),464 response = {465 proxy: {466 to: 'where',467 mode: 'proxyOnce',468 predicateGenerators: [{469 inject: 'function(config) { throw Error("BOOM!!!"); }'470 }]471 }472 },473 request = { key: 'Test' };474 logger.error = function () {475 const message = util.format.apply(this, Array.prototype.slice.call(arguments));476 errorsLogged.push(message);477 };478 await stubs.add({ responses: [response] });479 const responseConfig = await getResponseFrom(stubs);480 try {481 await resolver.resolve(responseConfig, request, logger, {});482 assert.fail('should have thrown exception');483 }484 catch (error) {485 assert.strictEqual(error.message, 'invalid predicateGenerator injection');486 assert.ok(errorsLogged.indexOf('injection X=> Error: BOOM!!!') >= 0);487 }488 });489 it('should add xpath predicate parameter in predicateGenerators with one match', async function () {490 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },491 stubs = createStubsRepository(),492 resolver = ResponseResolver.create(stubs, proxy),493 logger = Logger.create(),494 response = {495 proxy: {496 to: 'where',497 predicateGenerators: [{498 matches: { field: true },499 xpath: { selector: '//title' }500 }],501 mode: 'proxyOnce'502 }503 },504 request = { field: '<books><book><title>Harry Potter</title></book></books>' };505 await stubs.add({ responses: [response] });506 const responseConfig = await getResponseFrom(stubs);507 await resolver.resolve(responseConfig, request, logger, {});508 const stubList = await stubListFor(stubs);509 assert.deepEqual(stubList, [510 {511 predicates: [{512 deepEquals: { field: 'Harry Potter' },513 xpath: { selector: '//title' }514 }],515 responses: [{ is: { key: 'value' } }]516 },517 {518 responses: [response]519 }520 ]);521 });522 it('should add xpath predicate parameter in predicateGenerators with one match and a nested match key', async function () {523 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },524 stubs = createStubsRepository(),525 resolver = ResponseResolver.create(stubs, proxy),526 logger = Logger.create(),527 response = {528 proxy: {529 to: 'where',530 predicateGenerators: [{531 matches: { parent: { child: true } },532 xpath: { selector: '//title' }533 }],534 mode: 'proxyOnce'535 }536 },537 request = { parent: { child: '<books><book><title>Harry Potter</title></book></books>' } };538 await stubs.add({ responses: [response] });539 const responseConfig = await getResponseFrom(stubs);540 await resolver.resolve(responseConfig, request, logger, {});541 const stubList = await stubListFor(stubs);542 assert.deepEqual(stubList, [543 {544 predicates: [{545 equals: { parent: { child: 'Harry Potter' } },546 xpath: { selector: '//title' }547 }],548 responses: [{ is: { key: 'value' } }]549 },550 {551 responses: [response]552 }553 ]);554 });555 it('should add xpath predicate parameter in predicateGenerators with multiple matches', async function () {556 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },557 stubs = createStubsRepository(),558 resolver = ResponseResolver.create(stubs, proxy),559 logger = Logger.create(),560 response = {561 proxy: {562 to: 'where',563 predicateGenerators: [{564 matches: { field: true },565 xpath: {566 selector: '//isbn:title',567 ns: { isbn: 'http://schemas.isbn.org/ns/1999/basic.dtd' }568 }569 }],570 mode: 'proxyOnce'571 }572 },573 xml = '<root xmlns:isbn="http://schemas.isbn.org/ns/1999/basic.dtd">' +574 ' <isbn:book><isbn:title>Harry Potter</isbn:title></isbn:book>' +575 ' <isbn:book><isbn:title>The Hobbit</isbn:title></isbn:book>' +576 ' <isbn:book><isbn:title>Game of Thrones</isbn:title></isbn:book>' +577 '</root>',578 request = { field: xml };579 await stubs.add({ responses: [response] });580 const responseConfig = await getResponseFrom(stubs);581 await resolver.resolve(responseConfig, request, logger, {});582 const stubList = await stubListFor(stubs);583 assert.deepEqual(stubList, [584 {585 predicates: [{586 deepEquals: { field: ['Harry Potter', 'The Hobbit', 'Game of Thrones'] },587 xpath: {588 selector: '//isbn:title',589 ns: { isbn: 'http://schemas.isbn.org/ns/1999/basic.dtd' }590 }591 }],592 responses: [{ is: { key: 'value' } }]593 },594 {595 responses: [response]596 }597 ]);598 });599 it('should add xpath predicate parameter in predicateGenerators even if no xpath match', async function () {600 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },601 stubs = createStubsRepository(),602 resolver = ResponseResolver.create(stubs, proxy),603 logger = Logger.create(),604 response = {605 proxy: {606 to: 'where',607 predicateGenerators: [{608 matches: { field: true },609 xpath: { selector: '//title' }610 }],611 mode: 'proxyOnce'612 }613 },614 request = { field: '<books />' };615 await stubs.add({ responses: [response] });616 const responseConfig = await getResponseFrom(stubs);617 await resolver.resolve(responseConfig, request, logger, {});618 const stubList = await stubListFor(stubs);619 assert.deepEqual(stubList, [620 {621 predicates: [{622 deepEquals: { field: '' },623 xpath: { selector: '//title' }624 }],625 responses: [{ is: { key: 'value' } }]626 },627 {628 responses: [response]629 }630 ]);631 });632 it('should add xpath predicate parameter in predicateGenerators even if scalar xpath match', async function () {633 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },634 stubs = createStubsRepository(),635 resolver = ResponseResolver.create(stubs, proxy),636 logger = Logger.create(),637 response = {638 proxy: {639 to: 'where',640 predicateGenerators: [{641 matches: { field: true },642 xpath: { selector: 'count(//title)' }643 }],644 mode: 'proxyOnce'645 }646 },647 request = { field: '<doc><title>first</title><title>second</title></doc>' };648 await stubs.add({ responses: [response] });649 const responseConfig = await getResponseFrom(stubs);650 await resolver.resolve(responseConfig, request, logger, {});651 const stubList = await stubListFor(stubs);652 assert.deepEqual(stubList, [653 {654 predicates: [{655 deepEquals: { field: 2 },656 xpath: { selector: 'count(//title)' }657 }],658 responses: [{ is: { key: 'value' } }]659 },660 {661 responses: [response]662 }663 ]);664 });665 it('should add xpath predicate parameter in predicateGenerators even if boolean match', async function () {666 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },667 stubs = createStubsRepository(),668 resolver = ResponseResolver.create(stubs, proxy),669 logger = Logger.create(),670 response = {671 proxy: {672 to: 'where',673 predicateGenerators: [{674 matches: { field: true },675 xpath: { selector: 'boolean(//title)' }676 }],677 mode: 'proxyOnce'678 }679 },680 request = { field: '<doc></doc>' };681 await stubs.add({ responses: [response] });682 const responseConfig = await getResponseFrom(stubs);683 await resolver.resolve(responseConfig, request, logger, {});684 const stubList = await stubListFor(stubs);685 assert.deepEqual(stubList, [686 {687 predicates: [{688 deepEquals: { field: false },689 xpath: { selector: 'boolean(//title)' }690 }],691 responses: [{ is: { key: 'value' } }]692 },693 {694 responses: [response]695 }696 ]);697 });698 it('should add jsonpath predicate parameter in predicateGenerators with one match', async function () {699 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },700 stubs = createStubsRepository(),701 resolver = ResponseResolver.create(stubs, proxy),702 logger = Logger.create(),703 response = {704 proxy: {705 to: 'where',706 predicateGenerators: [{707 matches: { field: true },708 jsonpath: { selector: '$..title' }709 }],710 mode: 'proxyOnce'711 }712 },713 request = { field: { title: 'Harry Potter' } };714 await stubs.add({ responses: [response] });715 const responseConfig = await getResponseFrom(stubs);716 await resolver.resolve(responseConfig, request, logger, {});717 const stubList = await stubListFor(stubs);718 assert.deepEqual(stubList, [719 {720 predicates: [{721 deepEquals: { field: 'Harry Potter' },722 jsonpath: { selector: '$..title' }723 }],724 responses: [{ is: { key: 'value' } }]725 },726 {727 responses: [response]728 }729 ]);730 });731 it('should add jsonpath predicate parameter in predicateGenerators with multiple matches', async function () {732 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },733 stubs = createStubsRepository(),734 resolver = ResponseResolver.create(stubs, proxy),735 logger = Logger.create(),736 response = {737 proxy: {738 to: 'where',739 predicateGenerators: [{740 matches: { field: true },741 jsonpath: { selector: '$.books[*].title' }742 }],743 mode: 'proxyOnce'744 }745 },746 request = {747 field: {748 books: [749 { title: 'Harry Potter' },750 { title: 'The Hobbit' },751 { title: 'Game of Thrones' }752 ]753 }754 };755 await stubs.add({ responses: [response] });756 const responseConfig = await getResponseFrom(stubs);757 await resolver.resolve(responseConfig, request, logger, {});758 const stubList = await stubListFor(stubs);759 assert.deepEqual(stubList, [760 {761 predicates: [{762 deepEquals: { field: ['Harry Potter', 'The Hobbit', 'Game of Thrones'] },763 jsonpath: { selector: '$.books[*].title' }764 }],765 responses: [{ is: { key: 'value' } }]766 },767 {768 responses: [response]769 }770 ]);771 });772 it('should add jsonpath predicate parameter in predicateGenerators with no match', async function () {773 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },774 stubs = createStubsRepository(),775 resolver = ResponseResolver.create(stubs, proxy),776 logger = Logger.create(),777 response = {778 proxy: {779 to: 'where',780 predicateGenerators: [{781 matches: { field: true },782 jsonpath: { selector: '$..title' }783 }],784 mode: 'proxyOnce'785 }786 },787 request = { field: false };788 await stubs.add({ responses: [response] });789 const responseConfig = await getResponseFrom(stubs);790 await resolver.resolve(responseConfig, request, logger, {});791 const stubList = await stubListFor(stubs);792 assert.deepEqual(stubList, [793 {794 predicates: [{795 deepEquals: { field: '' },796 jsonpath: { selector: '$..title' }797 }],798 responses: [{ is: { key: 'value' } }]799 },800 {801 responses: [response]802 }803 ]);804 });805 it('should not ignored a field from the request before recording', async function () {806 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },807 stubs = createStubsRepository(),808 resolver = ResponseResolver.create(stubs, proxy),809 logger = Logger.create(),810 response = {811 proxy: {812 to: 'where',813 predicateGenerators: [{814 matches: { query: true },815 ignore: { query: 'deleteAt' }816 }],817 mode: 'proxyOnce'818 }819 },820 request = { query: { limit: 100, enhanced: true, endDate: '2017-10-11', startDate: '2017-09-07' } };821 await stubs.add({ responses: [response] });822 const responseConfig = await getResponseFrom(stubs);823 await resolver.resolve(responseConfig, request, logger, {});824 const stubList = await stubListFor(stubs);825 assert.deepEqual(stubList, [826 {827 predicates: [{828 deepEquals: request829 }],830 responses: [{ is: { key: 'value' } }]831 },832 {833 responses: [response]834 }835 ]);836 });837 it('should ignore one specific field from the request before recording', async function () {838 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },839 stubs = createStubsRepository(),840 resolver = ResponseResolver.create(stubs, proxy),841 logger = Logger.create(),842 response = {843 proxy: {844 to: 'where',845 predicateGenerators: [{846 matches: { query: true },847 ignore: { query: 'startDate' }848 }],849 mode: 'proxyOnce'850 }851 },852 request = { query: { limit: 100, enhanced: true, endDate: '2017-10-11', startDate: '2017-09-07' } };853 await stubs.add({ responses: [response] });854 const responseConfig = await getResponseFrom(stubs);855 await resolver.resolve(responseConfig, request, logger, {});856 const stubList = await stubListFor(stubs);857 assert.deepEqual(stubList, [858 {859 predicates: [{860 deepEquals: { query: { limit: 100, enhanced: true, endDate: '2017-10-11' } }861 }],862 responses: [{ is: { key: 'value' } }]863 },864 {865 responses: [response]866 }867 ]);868 });869 it('should ignore multiple fields from the request before recording', async function () {870 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },871 stubs = createStubsRepository(),872 resolver = ResponseResolver.create(stubs, proxy),873 logger = Logger.create(),874 response = {875 proxy: {876 to: 'where',877 predicateGenerators: [{878 matches: { field: true },879 ignore: { field: { mutable: { date: ['deleteAt', 'endDate'] } } }880 }],881 mode: 'proxyOnce'882 }883 },884 request = { field: { immutable: { id: '63e3a55f-ee87-457f-b808-cf986c28b312', categories: 'promotion-2021' }, mutable: { date: { endDate: '2017-10-11', startDate: '2017-09-07', creatAt: '2017-08-06', deleteAt: '2017-10-11' } } } };885 await stubs.add({ responses: [response] });886 const responseConfig = await getResponseFrom(stubs);887 await resolver.resolve(responseConfig, request, logger, {});888 const stubList = await stubListFor(stubs);889 assert.deepEqual(stubList, [890 {891 predicates: [{892 deepEquals: { field: { immutable: { id: '63e3a55f-ee87-457f-b808-cf986c28b312', categories: 'promotion-2021' }, mutable: { date: { startDate: '2017-09-07', creatAt: '2017-08-06' } } } }893 }],894 responses: [{ is: { key: 'value' } }]895 },896 {897 responses: [response]898 }899 ]);900 });901 it('should log warning if request not JSON', async function () {902 const proxy = { to: mock().returns(Promise.resolve({ key: 'value' })) },903 stubs = createStubsRepository(),904 resolver = ResponseResolver.create(stubs, proxy),905 logger = Logger.create(),906 response = {907 proxy: {908 to: 'where',909 predicateGenerators: [{910 matches: { field: true },911 jsonpath: { selector: '$..title' }912 }],913 mode: 'proxyOnce'914 }915 },916 request = { field: 'Hello, world' };917 await stubs.add({ responses: [response] });918 const responseConfig = await getResponseFrom(stubs);919 await resolver.resolve(responseConfig, request, logger, {});920 const stubList = await stubListFor(stubs);921 assert.deepEqual(stubList, [922 {923 predicates: [{924 deepEquals: { field: '' },925 jsonpath: { selector: '$..title' }926 }],927 responses: [{ is: { key: 'value' } }]928 },929 {930 responses: [response]931 }932 ]);933 logger.warn.assertLogged('Cannot parse as JSON: "Hello, world"');934 });935 it('should allow "inject" response', async function () {936 const stubs = createStubsRepository(),937 resolver = ResponseResolver.create(stubs, {}),938 logger = Logger.create(),939 fn = request => request.data + ' injected',940 responseConfig = { inject: fn.toString() },941 request = { data: 'request' };942 const response = await resolver.resolve(responseConfig, request, logger, {});943 assert.strictEqual(response, 'request injected');944 });945 it('should log injection exceptions', async function () {946 const stubs = createStubsRepository(),947 resolver = ResponseResolver.create(stubs, {}),948 logger = Logger.create(),949 fn = () => {950 throw Error('BOOM!!!');951 },952 responseConfig = { inject: fn };953 try {954 await resolver.resolve(responseConfig, {}, logger, {});955 assert.fail('should not have resolved');956 }957 catch (error) {958 assert.strictEqual(error.message, 'invalid response injection');959 logger.error.assertLogged('injection X=> Error: BOOM!!!');960 }961 });962 it('should allow injection request state across calls to resolve', async function () {963 const stubs = createStubsRepository(),964 resolver = ResponseResolver.create(stubs, {}),965 logger = Logger.create(),966 fn = (request, state) => {967 state.counter = state.counter || 0;968 state.counter += 1;969 return state.counter;970 },971 responseConfig = { inject: fn.toString() },972 request = { key: 'request' };973 const firstResponse = await resolver.resolve(responseConfig, request, logger, {}),974 secondResponse = await resolver.resolve(responseConfig, request, logger, []);975 assert.strictEqual(firstResponse, 1);976 assert.strictEqual(secondResponse, 2);977 });978 it('should allow injection imposter state across calls to resolve', async function () {979 const stubs = createStubsRepository(),980 resolver = ResponseResolver.create(stubs, {}),981 mockedLogger = Logger.create(),982 imposterState = { foo: 'bar', counter: 0 },983 fn = (request, localState, logger, deferred, globalState) => {984 globalState.foo = 'barbar';985 globalState.counter += 1;986 return globalState.foo + globalState.counter;987 },988 responseConfig = { inject: fn.toString() },989 request = { key: 'request' };990 const firstResponse = await resolver.resolve(responseConfig, request, mockedLogger, imposterState),991 secondResponse = await resolver.resolve(responseConfig, request, mockedLogger, imposterState);992 assert.strictEqual(firstResponse, 'barbar1');993 assert.strictEqual(secondResponse, 'barbar2');994 });995 it('should allow wait behavior', async function () {996 const start = Date.now();997 const stubs = createStubsRepository(),998 resolver = ResponseResolver.create(stubs, {}),999 logger = Logger.create(),1000 responseConfig = {1001 is: 'value',1002 behaviors: [{ wait: 50 }]1003 },1004 request = { key: 'request' };1005 await resolver.resolve(responseConfig, request, logger, {});1006 const elapsed = Date.now() - start;1007 // allow some approximation1008 assert.ok(elapsed >= 45, 'Did not wait longer than 50 ms, only waited for ' + elapsed);1009 });1010 it('should allow wait behavior based on a function', async function () {1011 const start = Date.now();1012 const stubs = createStubsRepository(),1013 resolver = ResponseResolver.create(stubs, {}),1014 logger = Logger.create(),1015 fn = () => 50,1016 responseConfig = {1017 is: 'value',1018 behaviors: [{ wait: fn.toString() }]1019 },1020 request = { key: 'request' };1021 await resolver.resolve(responseConfig, request, logger, {});1022 const elapsed = Date.now() - start;1023 // allow for some lack of precision1024 assert.ok(elapsed >= 48, 'Did not wait longer than 50 ms, only waited for ' + elapsed);1025 });1026 it('should reject the promise when the wait function fails', async function () {1027 const stubs = createStubsRepository(),1028 resolver = ResponseResolver.create(stubs, {}),1029 logger = Logger.create(),1030 fn = () => {1031 throw new Error('Error message');1032 },1033 responseConfig = {1034 is: 'value',1035 behaviors: [{ wait: fn.toString() }]1036 },1037 request = { key: 'request' };1038 try {1039 await resolver.resolve(responseConfig, request, logger, {});1040 assert.fail('Promise resolved, should have been rejected');1041 }1042 catch (error) {1043 assert.equal(error.message, 'invalid wait injection');1044 }1045 });1046 it('should allow asynchronous injection', async function () {1047 const stubs = createStubsRepository(),1048 resolver = ResponseResolver.create(stubs, {}),1049 fn = (request, state, logger, callback) => {1050 setTimeout(() => {1051 callback('value');1052 }, 1);1053 },1054 responseConfig = { inject: fn },1055 request = { key: 'request' };1056 const response = await resolver.resolve(responseConfig, request, { debug: mock() }, {});1057 assert.strictEqual(response, 'value');1058 });1059 it('should not be able to change state through inject', async function () {1060 const stubs = createStubsRepository(),1061 resolver = ResponseResolver.create(stubs, {}),1062 logger = Logger.create(),1063 fn = request => {1064 request.key = 'CHANGED';1065 return 0;1066 },1067 responseConfig = { inject: fn.toString() },1068 request = { key: 'ORIGINAL' };1069 await resolver.resolve(responseConfig, request, logger, {});1070 assert.strictEqual(request.key, 'ORIGINAL');1071 });1072 it('should not run injection during dry run validation', async function () {1073 const stubs = createStubsRepository(),1074 resolver = ResponseResolver.create(stubs, {}),1075 logger = Logger.create(),1076 fn = () => {1077 throw Error('BOOM!!!');1078 },1079 responseConfig = { inject: fn.toString() },1080 request = { isDryRun: true };1081 const response = await resolver.resolve(responseConfig, request, logger, {});1082 assert.deepEqual(response, {});1083 });1084 it('should throw error if multiple response types given', async function () {1085 const stubs = createStubsRepository(),1086 resolver = ResponseResolver.create(stubs, {}),1087 logger = Logger.create(),1088 responseConfig = { is: 'value', proxy: { to: 'http://www.google.com' } };1089 try {1090 await resolver.resolve(responseConfig, {}, logger, {});1091 assert.fail('should not have resolved');1092 }1093 catch (error) {1094 assert.strictEqual(error.message, 'each response object must have only one response type');1095 }1096 });1097 it('should throw error if fault used with other response type', async function () {1098 const stubs = createStubsRepository(),1099 resolver = ResponseResolver.create(stubs, {}),1100 logger = Logger.create(),1101 responseConfig = { fault: 'value', proxy: { to: 'http://www.google.com' } };1102 try {1103 await resolver.resolve(responseConfig, {}, logger, {});1104 assert.fail('should not have resolved');1105 }1106 catch (error) {1107 assert.strictEqual(error.message, 'each response object must have only one response type');1108 }1109 });1110 });1111 describe('#resolveProxy', function () {1112 function jsonResponse (response) {1113 delete response.recordMatch;1114 if (helpers.defined(response._proxyResponseTime)) {1115 delete response._proxyResponseTime;1116 }1117 return response;1118 }1119 it('should error if called with invalid proxyResolutionKey', async function () {1120 const stubs = createStubsRepository(),1121 resolver = ResponseResolver.create(stubs, null, 'CALLBACK-URL'),1122 logger = Logger.create();1123 try {1124 await resolver.resolveProxy({ field: 'value' }, 0, logger);1125 assert.fail('should have errored');1126 }1127 catch (error) {1128 assert.deepEqual(error, {1129 code: 'no such resource',1130 message: 'invalid proxy resolution key',1131 source: 'CALLBACK-URL/0'1132 });1133 logger.error.assertLogged('Invalid proxy resolution key: 0');1134 }1135 });1136 it('should save new response in front of proxy for "proxyOnce" mode', async function () {1137 const stubs = createStubsRepository(),1138 resolver = ResponseResolver.create(stubs, null, 'CALLBACK-URL'),1139 logger = Logger.create(),1140 responseConfig = { proxy: { to: 'where', mode: 'proxyOnce' } },1141 request = {};1142 await stubs.add({ responses: [responseConfig] });1143 responseConfig.stubIndex = () => Promise.resolve(0);1144 const firstResponse = await resolver.resolve(responseConfig, request, logger, {});1145 const proxyResolutionKey = parseInt(firstResponse.callbackURL.replace('CALLBACK-URL/', ''));1146 const secondResponse = await resolver.resolveProxy({ data: 'RESPONSE' }, proxyResolutionKey, logger),1147 all = await stubs.toJSON(),1148 stubResponses = all.map(stub => proxyResponses(stub.responses));1149 assert.deepEqual(jsonResponse(secondResponse), { data: 'RESPONSE' });1150 delete responseConfig.stubIndex;1151 assert.deepEqual(stubResponses, [1152 [{ is: { data: 'RESPONSE' } }],1153 [responseConfig]1154 ]);1155 });1156 it('should save new response after proxy for "proxyAlways" mode', async function () {1157 const stubs = createStubsRepository(),1158 resolver = ResponseResolver.create(stubs, null, 'CALLBACK-URL'),1159 logger = Logger.create(),1160 responseConfig = { proxy: { to: 'where', mode: 'proxyAlways' } },1161 request = {};1162 await stubs.add({ responses: [responseConfig] });1163 responseConfig.stubIndex = () => Promise.resolve(0);1164 const firstResponse = await resolver.resolve(responseConfig, request, logger, {});1165 const proxyResolutionKey = parseInt(firstResponse.callbackURL.replace('CALLBACK-URL/', ''));1166 const secondResponse = await resolver.resolveProxy({ data: 'RESPONSE' }, proxyResolutionKey, logger),1167 all = await stubs.toJSON(),1168 stubResponses = all.map(stub => proxyResponses(stub.responses));1169 assert.deepEqual(jsonResponse(secondResponse), { data: 'RESPONSE' });1170 delete responseConfig.stubIndex;1171 assert.deepEqual(stubResponses, [1172 [responseConfig],1173 [{ is: { data: 'RESPONSE' } }]1174 ]);1175 });1176 it('should run behaviors from original proxy config on proxy response before recording it', async function () {1177 const decorateFunc = (request, response) => { response.data += '-DECORATED'; },1178 stubs = createStubsRepository(),1179 resolver = ResponseResolver.create(stubs, null, 'CALLBACK-URL'),1180 logger = Logger.create(),1181 proxyResponse = {1182 proxy: { to: 'where', mode: 'proxyOnce' },1183 behaviors: [{ decorate: decorateFunc.toString() }]1184 },1185 request = {};1186 await stubs.add({ responses: [proxyResponse] });1187 const responseConfig = await getResponseFrom(stubs),1188 firstResponse = await resolver.resolve(responseConfig, request, logger, {}),1189 proxyResolutionKey = parseInt(firstResponse.callbackURL.replace('CALLBACK-URL/', '')),1190 secondResponse = await resolver.resolveProxy({ data: 'RESPONSE' }, proxyResolutionKey, logger),1191 all = await stubs.toJSON(),1192 stubResponses = all.map(stub => proxyResponses(stub.responses));1193 assert.deepEqual(jsonResponse(secondResponse), { data: 'RESPONSE-DECORATED' });1194 assert.deepEqual(stubResponses, [1195 [{ is: { data: 'RESPONSE-DECORATED' } }],1196 [proxyResponse]1197 ]);1198 });1199 it('should add wait behavior based on the proxy resolution time', async function () {1200 const stubs = createStubsRepository(),1201 resolver = ResponseResolver.create(stubs, null, 'CALLBACK-URL'),1202 logger = Logger.create(),1203 proxyResponse = { proxy: { to: 'where', mode: 'proxyOnce', addWaitBehavior: true } },1204 request = {};1205 await stubs.add({ responses: [proxyResponse] });1206 const responseConfig = await getResponseFrom(stubs),1207 response = await resolver.resolve(responseConfig, request, logger, {}),1208 proxyResolutionKey = parseInt(response.callbackURL.replace('CALLBACK-URL/', ''));1209 await delay(100);1210 await resolver.resolveProxy({ data: 'RESPONSE' }, proxyResolutionKey, logger);1211 const all = await stubs.toJSON(),1212 stubResponses = all.map(stub => stub.responses),1213 wait = stubResponses[0][0].is._proxyResponseTime;1214 assert.ok(wait > 90); // allow some variability1215 assert.deepEqual(stubResponses, [1216 [{ is: { data: 'RESPONSE', _proxyResponseTime: wait }, behaviors: [{ wait: wait }] }],1217 [proxyResponse]1218 ]);1219 });1220 it('should not resolve the same proxyResolutionKey twice', async function () {1221 const stubs = createStubsRepository(),1222 resolver = ResponseResolver.create(stubs, null, 'CALLBACK-URL'),1223 logger = Logger.create(),1224 proxyResponse = { proxy: { to: 'where' } },1225 request = {};1226 await stubs.add({ responses: [proxyResponse] });1227 const responseConfig = await getResponseFrom(stubs),1228 response = await resolver.resolve(responseConfig, request, logger, {}),1229 proxyResolutionKey = parseInt(response.callbackURL.replace('CALLBACK-URL/', ''));1230 await resolver.resolveProxy({ data: 'RESPONSE' }, proxyResolutionKey, logger);1231 try {1232 await resolver.resolveProxy({ data: 'RESPONSE' }, proxyResolutionKey, logger);1233 assert.fail('should have errored');1234 }1235 catch (error) {1236 assert.deepEqual(error, {1237 code: 'no such resource',1238 message: 'invalid proxy resolution key',1239 source: 'CALLBACK-URL/0'1240 });1241 logger.error.assertLogged('Invalid proxy resolution key: 0');...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...12 resolve(server)13 })14 })15}16async function getResponseFrom(endpoint) {17 const port = await getPort()18 const server = await startServer(port)19 const res = await fetch(`http://localhost:${port}${endpoint}`)20 server.close()21 return res22}23function genericTest(endpoint, responseText) {24 return async t => {25 const res = await getResponseFrom(endpoint)26 const data = await res.text()27 t.is(data, responseText)28 }29}30function genericStatusCodeTest(endpoint, expectedCode) {31 return async t => {32 const res = await getResponseFrom(endpoint)33 const code = res.status34 t.is(code, expectedCode)35 }36}37test(38 'Creates an index.js endpoint at /',39 genericTest('/', 'hello from index.js')40)41test('Creates a named endpoint', genericTest('/foo', 'hello from foo.js'))42test(43 'Supports nested folders with index.js support',44 genericTest('/bar', 'hello from bar/index.js')45)46test(47 'Supports typescript',48 genericTest('/typescript', 'hello from typescript.ts')49)50test(51 'Returns 404 for empty endpoint',52 genericStatusCodeTest('/idontexist', 404)53)54test(55 'Returns custom status code as number',56 genericStatusCodeTest('/code', 203)57)58test('Supports async functions', genericTest('/async', 'hello from async.ts'))59test('Supports strings', genericTest('/string', 'just a string'))60test(61 'Ignores result when headers have been sent',62 genericTest('/headers-sent', 'first')63)64test('Sends parsed query.params', genericTest('/query?id=bar', 'bar'))65test('Supports json and sends correct data type', async t => {66 const res = await getResponseFrom('/json')67 const json = await res.json()68 t.is(json, { custom: 'foo' })...

Full Screen

Full Screen

kkApiUtils.js

Source:kkApiUtils.js Github

copy

Full Screen

...13 method: 'get',14 responseType: 'stream'15 }).catch(err => {console.log(err)});16}17function getResponseFrom(url, method){18 return Axios({19 url,20 method21 }).catch(err => {console.log(err)});22}23exports.getImageDataStream = getImageDataStream;24exports.getResponseFrom = getResponseFrom;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposter = {3 {4 {5 is: {6 }7 }8 }9};10mb.create(imposter).then(function (server) {11 server.get('/path', function (req, res) {12 res.end('Hello, world!');13 });14}).then(function (response) {15 console.log(response.body);16});17var mb = require('mountebank');18var imposter = {19 {20 {21 is: {22 }23 }24 }25};26mb.create(imposter).then(function (server) {27}).then(function (response) {28 console.log(response.body);29});30}).catch(function (

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

1const {getResponseFrom} = require('mountebank');2const response = await getResponseFrom({3});4console.log(response);5const {createImposter} = require('mountebank');6const response = await createImposter({7 {8 {9 is: {10 }11 }12 }13});14console.log(response);15const {deleteImposter} = require('mountebank');16const response = await deleteImposter({17});18console.log(response);19Let’s block ads! (Why?)

Full Screen

Using AI Code Generation

copy

Full Screen

1var mbHelper = require('./mountebank-helper');2.then(function(response){3 console.log(response);4});5var request = require('request-promise');6module.exports = {7 getResponseFrom: function(url){8 return request(url);9 }10}11{12 {13 "query": {},14 "headers": {15 "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",16 "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",17 "accept-language": "en-US,en;q=0.8,hi;q=0.6"18 },19 }20 {21 "is": {22 "headers": {23 },24 "body": {25 }26 },27 "_links": {28 "self": {29 }30 }31 }32 {33 {34 "equals": {35 }36 }37 {38 "is": {39 "headers": {40 },41 "body": {42 }43 }44 }

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var getResponseFrom = function(url, callback) {3 request(url, function(err, response, body) {4 if (err) {5 console.log('error:', err);6 callback(err);7 } else {8 console.log('statusCode:', response && response.statusCode);9 callback(null, body);10 }11 });12};13module.exports = getResponseFrom;14var getResponseFrom = require('./test.js');15describe('getResponseFrom', function() {16 it('returns a response', function(done) {17 expect(err).toBeNull();18 expect(response).toBeDefined();19 done();20 });21 });22});

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposter = require('mountebank').create();2var port = 4545;3imposter.create(port, function() {4 console.log(response);5 });6});7var imposter = require('mountebank').create();8var port = 4545;9imposter.create(port, function() {10 imposter.getResponseFrom('/test', function(response) {11 console.log(response);12 });13});14var imposter = require('mountebank').create();15var port = 4545;16imposter.create(port, function() {17 imposter.getResponseFrom('/test', function(response) {18 console.log(response);19 });20});21var imposter = require('mountebank').create();22var port = 4545;23imposter.create(port, function() {24 imposter.getResponseFrom('/test', function(response) {25 console.log(response);26 });27});

Full Screen

Using AI Code Generation

copy

Full Screen

1const mbHelper = require('./mbHelper');2const mbHelperObj = new mbHelper();3const rp = require('request-promise');4const assert = require('assert');5const path = require('path');6const mbPort = 2525;7const mbHost = 'localhost';8const mbProtocol = 'http';9const config = {10};11const test = async () => {12 await mbHelperObj.startMb(config);13 const imposter = {14 {15 {16 is: {17 }18 }19 }20 };21 const imposterResponse = await mbHelperObj.createImposter(imposter);22 assert.strictEqual(imposterResponse.statusCode, 201);23 const imposterUrl = `${mbUrl}/imposters/${imposterResponse.body.port}`;24 const response = await rp(imposterUrl);25 assert.strictEqual(response, 'Hello, World!');26 await mbHelperObj.deleteImposter(imposterResponse.body.port);27 await mbHelperObj.stopMb();28};29test();30const mb = require('mountebank');31const path = require('path');32const mbHelper = function () {33 this.mb = mb;34 this.path = path;35};36mbHelper.prototype.startMb = function (config) {37 return this.mb.start({38 pidfile: this.path.resolve('./mb.pid'),39 logfile: this.path.resolve('./mb.log'),40 protofile: this.path.resolve('./mb.proto'),41 });42};43mbHelper.prototype.stopMb = function () {44 return this.mb.stop();45};46mbHelper.prototype.createImposter = function (imposter) {47 return this.mb.create(imposter);48};49mbHelper.prototype.deleteImposter = function (port) {50 return this.mb.delete(port);51};52module.exports = mbHelper;

Full Screen

Using AI Code Generation

copy

Full Screen

1const { getResponseFrom } = require('mountebank');2const express = require('express');3const bodyParser = require('body-parser');4const app = express();5app.use(bodyParser.json());6app.post('/test', async (req, res) => {7 const response = await getResponseFrom({8 headers: { 'Content-Type': 'application/json' },9 body: JSON.stringify(req.body)10 });11 res.send(response.body);12});13app.listen(3000, () => console.log('Example app listening on port 3000!'));14const request = require('supertest');15const app = require('./test');16test('It should respond with the request body', async () => {17 const response = await request(app).post('/test').send({ name: 'test' });18 expect(response.body).toEqual({ name: 'test' });19});20const request = require('supertest');21const app = require('./test');22test('It should respond with the request body', async () => {23 const response = await request(app).post('/test').send({ name: 'test' });24 expect(response.body).toEqual({ name: 'test' });25});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { getResponseFrom } = require('mountebank');2const request = {3 headers: {4 },5 body: {6 }7};8getResponseFrom(request)9 .then(response => {10 })11 .catch(error => {12 });

Full Screen

Using AI Code Generation

copy

Full Screen

1var mbHelper = require('mountebank-helper');2var assert = require('assert');3var stub = {4 {5 is: {6 headers: {7 },8 body: {9 }10 }11 }12};13var mb = new mbHelper('localhost', 2525);14mb.addStub(stub).then(function (response) {15 var request = {16 };17 return mb.getResponseFrom(request);18}).then(function (response) {19 assert.equal(response.statusCode, 200);20}).catch(function (error) {21 console.log(error);22});23var mbHelper = require('mountebank-helper');24var assert = require('assert');25var stub = {26 {27 is: {28 headers: {29 },30 body: {31 }32 }33 }34};35var mb = new mbHelper('localhost', 2525);36mb.addStub(stub).then(function (response) {37 var request = {38 };39 return mb.getResponseFrom(request);40}).then(function (response) {41 assert.equal(response.statusCode, 200);42}).catch(function (error) {43 console.log(error);44});45var mbHelper = require('mountebank-helper');46var assert = require('assert');47var stub = {48 {49 is: {50 headers: {

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