How to use middlewareFn method in mountebank

Best JavaScript code snippet using mountebank

composer.d.ts

Source:composer.d.ts Github

copy

Full Screen

1/** @format */2import * as tt from './telegram-types.d'3import { TelegrafContext } from './context'4type MaybeArray<T> = T | T[]5type MaybePromise<T> = T | Promise<T>6type NormalizedTrigger<TContext> = (value: string, ctx: TContext) => RegExpExecArray | null7type HearsTriggers<TContext> = MaybeArray<string | RegExp | NormalizedTrigger<TContext>>8type Predicate<TContext> = (ctx: TContext) => MaybePromise<boolean>9type BranchPredicate<TContext> = boolean | Predicate<TContext>10export interface MiddlewareFn<TContext extends TelegrafContext> {11 /*12 next's parameter is in a contravariant position, and thus, trying to type it13 prevents assigning `MiddlewareFn<ContextMessageUpdate>`14 to `MiddlewareFn<CustomContext>`.15 Middleware passing the parameter should be a separate type instead.16 */17 (ctx: TContext, next: () => Promise<void>): void | Promise<unknown>18}19export interface MiddlewareObj<TContext extends TelegrafContext> {20 middleware(): MiddlewareFn<TContext>21}22export type Middleware<TContext extends TelegrafContext> =23 | MiddlewareFn<TContext>24 | MiddlewareObj<TContext>25export declare class Composer<TContext extends TelegrafContext>26 implements MiddlewareObj<TContext> {27 constructor(...middlewares: ReadonlyArray<Middleware<TContext>>)28 /**29 * Registers a middleware.30 */31 use(...middlewares: ReadonlyArray<Middleware<TContext>>): this32 /**33 * Registers middleware for provided update type.34 */35 on(36 updateTypes: MaybeArray<tt.UpdateType | tt.MessageSubTypes>,37 ...middlewares: ReadonlyArray<Middleware<TContext>>38 ): this39 /**40 * Registers middleware for handling text messages.41 */42 hears(43 triggers: HearsTriggers<TContext>,44 ...middlewares: ReadonlyArray<Middleware<TContext>>45 ): this46 /**47 * Registers middleware for handling specified commands.48 */49 command(50 command: string | string[],51 ...middlewares: ReadonlyArray<Middleware<TContext>>52 ): this53 /**54 * Registers middleware for handling callbackQuery data with regular expressions55 */56 action(57 triggers: HearsTriggers<TContext>,58 ...middlewares: ReadonlyArray<Middleware<TContext>>59 ): this60 /**61 * Registers middleware for handling inlineQuery data with regular expressions62 */63 inlineQuery(64 triggers: HearsTriggers<TContext>,65 ...middlewares: ReadonlyArray<Middleware<TContext>>66 ): this67 /**68 * Registers middleware for handling callback_data actions with game query.69 */70 gameQuery(...middlewares: ReadonlyArray<Middleware<TContext>>): this71 /**72 * Generates drop middleware.73 */74 drop<TContext extends TelegrafContext>(75 predicate: BranchPredicate<TContext>76 ): this77 /**78 * Generates filter middleware.79 */80 filter<TContext extends TelegrafContext>(81 predicate: BranchPredicate<TContext>82 ): this83 /**84 * Registers middleware for handling entities85 */86 entity<TContext extends TelegrafContext>(87 predicate: MaybeArray<tt.MessageEntityType> | ((entity: tt.MessageEntity, entityText: string, ctx: TContext) => MaybePromise<boolean>),88 ...middlewares: ReadonlyArray<Middleware<TContext>>89 ): this90 /**91 * Registers middleware for handling messages with matching emails.92 */93 email<TContext extends TelegrafContext>(94 email: HearsTriggers<TContext>,95 ...middlewares: ReadonlyArray<Middleware<TContext>>96 ): this97 /**98 * Registers middleware for handling messages with matching phones.99 */100 phone<TContext extends TelegrafContext>(101 number: HearsTriggers<TContext>,102 ...middlewares: ReadonlyArray<Middleware<TContext>>103 ): this104 /**105 * Registers middleware for handling messages with matching urls.106 */107 url<TContext extends TelegrafContext>(108 url: HearsTriggers<TContext>,109 ...middlewares: ReadonlyArray<Middleware<TContext>>110 ): this111 /**112 * Registers middleware for handling messages with matching text links.113 */114 textLink<TContext extends TelegrafContext>(115 link: HearsTriggers<TContext>,116 ...middlewares: ReadonlyArray<Middleware<TContext>>117 ): this118 /**119 * Registers middleware for handling messages with matching text mentions.120 */121 textMention<TContext extends TelegrafContext>(122 mention: HearsTriggers<TContext>,123 ...middlewares: ReadonlyArray<Middleware<TContext>>124 ): this125 /**126 * Registers middleware for handling messages with matching mentions.127 */128 mention<TContext extends TelegrafContext>(129 mention: HearsTriggers<TContext>,130 ...middlewares: ReadonlyArray<Middleware<TContext>>131 ): this132 /**133 * Registers middleware for handling messages with matching hashtags.134 */135 hashtag<TContext extends TelegrafContext>(136 hashtag: HearsTriggers<TContext>,137 ...middlewares: ReadonlyArray<Middleware<TContext>>138 ): this139 /**140 * Registers middleware for handling messages with matching cashtags.141 */142 cashtag<TContext extends TelegrafContext>(143 cashtag: HearsTriggers<TContext>,144 ...middlewares: ReadonlyArray<Middleware<TContext>>145 ): this146 /**147 * Registers middleware for handling /start command.148 */149 start(...middlewares: ReadonlyArray<Middleware<TContext>>): this150 /**151 * Registers middleware for handling /help command.152 */153 help(...middlewares: ReadonlyArray<Middleware<TContext>>): this154 /**155 * Registers middleware for handling /ыуеештпы command.156 */157 settings(...middlewares: ReadonlyArray<Middleware<TContext>>): this158 /**159 * Return the middleware created by this Composer160 */161 middleware(): MiddlewareFn<TContext>162 static reply(163 text: string,164 extra?: tt.ExtraSendMessage165 ): MiddlewareFn<TelegrafContext>166 static catchAll<TContext extends TelegrafContext>(167 ...middlewares: ReadonlyArray<Middleware<TContext>>168 ): MiddlewareFn<TContext>169 static catch<TContext extends TelegrafContext>(170 errorHandler: (error: Error, ctx: TContext) => void,171 ...middlewares: ReadonlyArray<Middleware<TContext>>172 ): MiddlewareFn<TContext>173 /**174 * Generates middleware that runs in the background.175 */176 static fork<TContext extends TelegrafContext>(177 middleware: Middleware<TContext>178 ): MiddlewareFn<TContext>179 /**180 * Generates tap middleware.181 */182 static tap<TContext extends TelegrafContext>(183 middleware: Middleware<TContext>184 ): MiddlewareFn<TContext>185 /**186 * Generates pass thru middleware.187 */188 static passThru(): MiddlewareFn<TelegrafContext>189 /**190 * Generates safe version of pass thru middleware.191 */192 static safePassThru(): MiddlewareFn<TelegrafContext>193 static lazy<TContext extends TelegrafContext>(194 factoryFn: (ctx: TContext) => MaybePromise<Middleware<TContext>>195 ): MiddlewareFn<TContext>196 static log(logFn?: (s: string) => void): MiddlewareFn<TelegrafContext>197 /**198 * @param predicate function that returns boolean or Promise<boolean>199 * @param trueMiddleware middleware to run if the predicate returns true200 * @param falseMiddleware middleware to run if the predicate returns false201 */202 static branch<TContext extends TelegrafContext>(203 predicate: BranchPredicate<TContext>,204 trueMiddleware: Middleware<TContext>,205 falseMiddleware: Middleware<TContext>206 ): MiddlewareFn<TContext>207 /**208 * Generates optional middleware.209 * @param predicate function that returns boolean or Promise<boolean>210 * @param middlewares middleware to run if the predicate returns true211 */212 static optional<TContext extends TelegrafContext>(213 predicate: BranchPredicate<TContext>,214 ...middlewares: ReadonlyArray<Middleware<TContext>>215 ): MiddlewareFn<TContext>216 /**217 * Generates filter middleware.218 */219 static filter<TContext extends TelegrafContext>(220 predicate: BranchPredicate<TContext>221 ): MiddlewareFn<TContext>222 /**223 * Generates drop middleware.224 */225 static drop<TContext extends TelegrafContext>(226 predicate: BranchPredicate<TContext>227 ): Middleware<TContext>228 static dispatch<229 C extends TelegrafContext,230 Handlers extends Record<string | number | symbol, Middleware<C>>231 >(232 routeFn: (ctx: C) => MaybePromise<keyof Handlers>,233 handlers: Handlers234 ): Middleware<C>235 /**236 * Generates middleware for handling provided update types.237 */238 static mount<TContext extends TelegrafContext>(239 updateType: tt.UpdateType | tt.UpdateType[],240 ...middlewares: ReadonlyArray<Middleware<TContext>>241 ): MiddlewareFn<TContext>242 static entity<TContext extends TelegrafContext>(243 predicate: MaybeArray<tt.MessageEntityType> | ((entity: tt.MessageEntity, entityText: string, ctx: TContext) => MaybePromise<boolean>),244 ...middlewares: ReadonlyArray<Middleware<TContext>>245 ): MiddlewareFn<TContext>246 static entityText<TContext extends TelegrafContext>(247 entityType: tt.MessageEntityType,248 triggers: HearsTriggers<TContext>,249 ...middlewares: ReadonlyArray<Middleware<TContext>>250 ): MiddlewareFn<TContext>251 /**252 * Generates middleware for handling messages with matching emails.253 */254 static email<TContext extends TelegrafContext>(255 email: HearsTriggers<TContext>,256 ...middlewares: ReadonlyArray<Middleware<TContext>>257 ): MiddlewareFn<TContext>258 /**259 * Generates middleware for handling messages with matching phones.260 */261 static phone<TContext extends TelegrafContext>(262 number: HearsTriggers<TContext>,263 ...middlewares: ReadonlyArray<Middleware<TContext>>264 ): MiddlewareFn<TContext>265 /**266 * Generates middleware for handling messages with matching urls.267 */268 static url<TContext extends TelegrafContext>(269 url: HearsTriggers<TContext>,270 ...middlewares: ReadonlyArray<Middleware<TContext>>271 ): MiddlewareFn<TContext>272 /**273 * Generates middleware for handling messages with matching text links.274 */275 static textLink<TContext extends TelegrafContext>(276 link: HearsTriggers<TContext>,277 ...middlewares: ReadonlyArray<Middleware<TContext>>278 ): MiddlewareFn<TContext>279 /**280 * Generates middleware for handling messages with matching text mentions.281 */282 static textMention<TContext extends TelegrafContext>(283 mention: HearsTriggers<TContext>,284 ...middlewares: ReadonlyArray<Middleware<TContext>>285 ): MiddlewareFn<TContext>286 /**287 * Generates middleware for handling messages with matching mentions.288 */289 static mention<TContext extends TelegrafContext>(290 mention: HearsTriggers<TContext>,291 ...middlewares: ReadonlyArray<Middleware<TContext>>292 ): MiddlewareFn<TContext>293 /**294 * Generates middleware for handling messages with matching hashtags.295 */296 static hashtag<TContext extends TelegrafContext>(297 hashtag: HearsTriggers<TContext>,298 ...middlewares: ReadonlyArray<Middleware<TContext>>299 ): MiddlewareFn<TContext>300 /**301 * Generates middleware for handling messages with matching cashtags.302 */303 static cashtag<TContext extends TelegrafContext>(304 cashtag: HearsTriggers<TContext>,305 ...middlewares: ReadonlyArray<Middleware<TContext>>306 ): MiddlewareFn<TContext>307 static match<TContext extends TelegrafContext>(308 triggers: NormalizedTrigger<TContext>[],309 ...middlewares: ReadonlyArray<Middleware<TContext>>310 ): MiddlewareFn<TContext>311 /**312 * Generates middleware for handling matching text messages.313 */314 static hears<TContext extends TelegrafContext>(315 triggers: HearsTriggers<TContext>,316 ...middlewares: ReadonlyArray<Middleware<TContext>>317 ): MiddlewareFn<TContext>318 /**319 * Generates middleware for handling messages with matching commands.320 */321 static command<TContext extends TelegrafContext>(322 command: string | string[],323 ...middlewares: ReadonlyArray<Middleware<TContext>>324 ): MiddlewareFn<TContext>325 /**326 * Generates middleware for handling messages with commands.327 */328 static command<TContext extends TelegrafContext>(329 ...middlewares: ReadonlyArray<Middleware<TContext>>330 ): MiddlewareFn<TContext>331 /**332 * Generates middleware for handling matching callback queries.333 */334 static action<TContext extends TelegrafContext>(335 triggers: HearsTriggers<TContext>,336 ...middlewares: ReadonlyArray<Middleware<TContext>>337 ): MiddlewareFn<TContext>338 /**339 * Generates middleware for handling matching inline queries.340 */341 static inlineQuery<TContext extends TelegrafContext>(342 triggers: HearsTriggers<TContext>,343 ...middlewares: ReadonlyArray<Middleware<TContext>>344 ): MiddlewareFn<TContext>345 static acl<TContext extends TelegrafContext>(346 status: number | number[] | BranchPredicate<TContext>,347 ...middlewares: ReadonlyArray<Middleware<TContext>>348 ): MiddlewareFn<TContext>349 static memberStatus<TContext extends TelegrafContext>(350 status: tt.ChatMemberStatus | tt.ChatMemberStatus[],351 ...middlewares: ReadonlyArray<Middleware<TContext>>352 ): MiddlewareFn<TContext>353 static admin<TContext extends TelegrafContext>(354 ...middlewares: ReadonlyArray<Middleware<TContext>>355 ): MiddlewareFn<TContext>356 static creator<TContext extends TelegrafContext>(357 ...middlewares: ReadonlyArray<Middleware<TContext>>358 ): MiddlewareFn<TContext>359 /**360 * Generates middleware running only in given chat types.361 */362 static chatType<TContext extends TelegrafContext>(363 type: tt.ChatType | tt.ChatType[],364 ...middlewares: ReadonlyArray<Middleware<TContext>>365 ): MiddlewareFn<TContext>366 /**367 * Generates middleware running only in private chats.368 */369 static privateChat<TContext extends TelegrafContext>(370 ...middlewares: ReadonlyArray<Middleware<TContext>>371 ): MiddlewareFn<TContext>372 /**373 * Generates middleware running only in groups and supergroups.374 */375 static groupChat<TContext extends TelegrafContext>(376 ...middlewares: ReadonlyArray<Middleware<TContext>>377 ): MiddlewareFn<TContext>378 static gameQuery<TContext extends TelegrafContext>(379 ...middlewares: ReadonlyArray<Middleware<TContext>>380 ): MiddlewareFn<TContext>381 static unwrap<TContext extends TelegrafContext>(382 middleware: Middleware<TContext>383 ): MiddlewareFn<TContext>384 /**385 * Compose middlewares returning a fully valid middleware comprised of all those which are passed.386 */387 static compose<TContext extends TelegrafContext>(388 middlewares: ReadonlyArray<Middleware<TContext>>389 ): MiddlewareFn<TContext>...

Full Screen

Full Screen

middlewareTest.js

Source:middlewareTest.js Github

copy

Full Screen

...19 response.setHeader = setHeader;20 });21 it('should not change header if not location header', function () {22 var middlewareFn = middleware.useAbsoluteUrls(9000);23 middlewareFn(request, response, next);24 response.setHeader('name', 'value');25 assert.ok(setHeader.wasCalledWith('name', 'value'));26 });27 it('should default location header to localhost with given port if no host header', function () {28 request.headers.host = '';29 var middlewareFn = middleware.useAbsoluteUrls(9000);30 middlewareFn(request, response, next);31 response.setHeader('location', '/');32 assert.ok(setHeader.wasCalledWith('location', 'http://localhost:9000/'));33 });34 it('should match location header regardless of case', function () {35 request.headers.host = '';36 var middlewareFn = middleware.useAbsoluteUrls(9000);37 middlewareFn(request, response, next);38 response.setHeader('LOCATION', '/');39 assert.ok(setHeader.wasCalledWith('LOCATION', 'http://localhost:9000/'));40 });41 it('should use the host header if present', function () {42 request.headers.host = 'mountebank.com';43 var middlewareFn = middleware.useAbsoluteUrls(9000);44 middlewareFn(request, response, next);45 response.setHeader('location', '/');46 assert.ok(setHeader.wasCalledWith('location', 'http://mountebank.com/'));47 });48 it('should do nothing if no response body links are present', function () {49 var middlewareFn = middleware.useAbsoluteUrls(9000);50 middlewareFn(request, response, next);51 response.send({ key: 'value' });52 assert.ok(send.wasCalledWith({ key: 'value' }));53 });54 it('should change response body links', function () {55 var middlewareFn = middleware.useAbsoluteUrls(9000);56 middlewareFn(request, response, next);57 response.send({ key: 'value', _links: { rel: { href: '/' } } });58 assert.ok(send.wasCalledWith({ key: 'value', _links: { rel: { href: 'http://localhost:9000/' } } }));59 });60 it('should change response nested body links', function () {61 var middlewareFn = middleware.useAbsoluteUrls(9000);62 middlewareFn(request, response, next);63 response.send({ key: { _links: { rel: { href: '/' } } } });64 assert.ok(send.wasCalledWith({ key: { _links: { rel: { href: 'http://localhost:9000/' } } } }));65 });66 it('should ignore null and undefined values', function () {67 var middlewareFn = middleware.useAbsoluteUrls(9000);68 middlewareFn(request, response, next);69 response.send({ first: null, second: undefined });70 assert.ok(send.wasCalledWith({ first: null }));71 });72 it('should not change html responses', function () {73 var middlewareFn = middleware.useAbsoluteUrls(9000);74 middlewareFn(request, response, next);75 response.send('<html _links="/"></html>');76 assert.ok(send.wasCalledWith('<html _links="/"></html>'));77 });78 });79 describe('#validateImposterExists', function () {80 it('should return 404 if imposter does not exist', function () {81 var middlewareFn = middleware.createImposterValidator({});82 request.params.id = 1;83 middlewareFn(request, response, next);84 assert.strictEqual(response.statusCode, 404);85 });86 it('should call next if imposter exists', function () {87 var imposters = { 1: {} },88 middlewareFn = middleware.createImposterValidator(imposters);89 request.params.id = 1;90 middlewareFn(request, response, next);91 assert(next.wasCalled());92 });93 });94 describe('#logger', function () {95 it('should log request at info level', function () {96 var log = { info: mock() },97 middlewareFn = middleware.logger(log, 'TEST MESSAGE');98 request = { url: '', headers: { accept: '' } };99 middlewareFn(request, {}, next);100 assert(log.info.wasCalledWith('TEST MESSAGE'));101 });102 it('should log request url and method', function () {103 var log = { info: mock() },104 middlewareFn = middleware.logger(log, 'MESSAGE WITH :method :url');105 request = { method: 'METHOD', url: 'URL', headers: { accept: '' } };106 middlewareFn(request, {}, next);107 assert(log.info.wasCalledWith('MESSAGE WITH METHOD URL'));108 });109 it('should not log static asset requests', function () {110 var log = { info: mock() },111 middlewareFn = middleware.logger(log, 'TEST');112 ['.js', '.css', '.png', '.ico'].forEach(function (ext) {113 request = { url: 'file' + ext, headers: { accept: '' } };114 middlewareFn(request, {}, next);115 assert(!log.info.wasCalled());116 });117 });118 it('should not log html requests', function () {119 var log = { info: mock() },120 middlewareFn = middleware.logger(log, 'TEST');121 request = { method: 'METHOD', url: 'URL', headers: { accept: 'text/html' } };122 middlewareFn(request, {}, next);123 assert(!log.info.wasCalled());124 });125 it('should not log AJAX requests', function () {126 var log = { info: mock() },127 middlewareFn = middleware.logger(log, 'TEST');128 request = { method: 'METHOD', url: 'URL', headers: { 'x-requested-with': 'XMLHttpRequest' } };129 middlewareFn(request, {}, next);130 assert(!log.info.wasCalled());131 });132 it('should call next', function () {133 var log = { info: mock() },134 middlewareFn = middleware.logger(log, 'TEST');135 request = { url: '', headers: { accept: '' } };136 middlewareFn(request, {}, next);137 assert(next.wasCalled());138 });139 });140 describe('#globals', function () {141 it('should pass variables to all render calls', function () {142 var render = mock(),143 middlewareFn = middleware.globals({ first: 1, second: 2 });144 response = { render: render };145 middlewareFn({}, response, next);146 response.render('view');147 assert(render.wasCalledWith('view', { first: 1, second: 2 }));148 });149 it('should merge variables to all render calls', function () {150 var render = mock(),151 middlewareFn = middleware.globals({ first: 1, second: 2 });152 response = { render: render };153 middlewareFn({}, response, next);154 response.render('view', { third: 3 });155 assert(render.wasCalledWith('view', { third: 3, first: 1, second: 2 }));156 });157 it('should overwrite variables of the same name', function () {158 var render = mock(),159 middlewareFn = middleware.globals({ key: 'global' });160 response = { render: render };161 middlewareFn({}, response, next);162 response.render('view', { key: 'local' });163 assert(render.wasCalledWith('view', { key: 'global' }));164 });165 });166 describe('#defaultIEtoHTML', function () {167 it('should not change accept header for non-IE user agents', function () {168 request.headers['user-agent'] = 'blah Chrome blah';169 request.headers.accept = 'original accept';170 middleware.defaultIEtoHTML(request, {}, mock());171 assert.strictEqual(request.headers.accept, 'original accept');172 });173 it('should change accept header for IE user agents', function () {174 request.headers['user-agent'] = 'blah MSIE blah';175 request.headers.accept = '*/*';...

Full Screen

Full Screen

middleware.spec.js

Source:middleware.spec.js Github

copy

Full Screen

1define([2 'superapi',3 'superagent'4], function (superapi, superagent) {5 'use strict';6 describe('middlewares', function () {7 describe('request', function () {8 var api;9 var server;10 beforeEach(function () {11 api = superapi.default({12 baseUrl: 'http://example.tld',13 services: {14 foo: {15 path:'foo'16 }17 },18 options: {19 timeout: 10020 }21 });22 api.agent = superagent;23 // add sinon to fake the XHR call24 server = sinon.fakeServer.create();25 });26 afterEach(function () {27 server.restore();28 server = null;29 api = null;30 });31 it('should execute middleware', function (done) {32 // configure response33 server.respondWith('GET',34 'http://example.tld/foo',35 [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']36 );37 var middlewareFn = sinon.spy(function (req) {});38 api.register('bar', middlewareFn);39 api.api.foo().then(function (res) {40 res.req.url.should.eql('http://example.tld/foo');41 middlewareFn.should.have.been.called;42 done();43 });44 server.respond();45 });46 it('should be able to modify request', function (done) {47 // configure response48 server.respondWith('GET',49 'http://example.tld/i-ve-been-hijacked',50 [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']51 );52 var middlewareFn = sinon.spy(function (req) {53 req.url = 'http://example.tld/i-ve-been-hijacked';54 });55 api.register('bar', middlewareFn);56 api.api.foo().then(function (res) {57 res.req.url.should.eql('http://example.tld/i-ve-been-hijacked');58 middlewareFn.should.have.been.called;59 done();60 });61 server.respond();62 });63 it('should access response on success', function (done) {64 // configure response65 server.respondWith('GET',66 'http://example.tld/foo',67 [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']68 );69 var responseHandler = sinon.spy(function (res) {70 res.req.url.should.eql('http://example.tld/foo');71 });72 var middlewareFn = sinon.spy(function (response) {73 responseHandler.should.have.been.called;74 response.status.should.eql(200);75 response.body.should.eql({result: 'ok'});76 done();77 });78 api.register('bar', function (req, next) {79 next().then(middlewareFn);80 });81 api.api.foo().then(responseHandler);82 server.respond();83 });84 it('should access response error', function (done) {85 // configure response86 // server.respondWith('GET',87 // 'http://example.tld/foo',88 // [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']89 // );90 var errorHandler = sinon.spy(function (error) {91 error.status.should.eql(404);92 });93 var middlewareFn = function (error) {94 errorHandler.should.have.been.called;95 done();96 };97 api.register('bar', function (req, next) {98 next().catch(middlewareFn);99 });100 api.api.foo().catch(errorHandler);101 server.respond();102 });103 it('should access abort error', function (done) {104 // configure response105 // server.respondWith('GET',106 // 'http://example.tld/foo',107 // [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']108 // );109 var errorHandler = sinon.spy(function (error) {110 error.should.have.property('aborted', true);111 });112 var middlewareFn = function (error) {113 errorHandler.should.have.been.called;114 error.should.have.property('aborted', true);115 done();116 };117 var request; // to memorize request118 api.register('bar', function (req, next) {119 request = req;120 next().catch(middlewareFn);121 });122 api.api.foo().catch(errorHandler);123 request.abort();124 });125 it('should access error on timeout', function (done) {126 // configure response127 // server.respondWith('GET',128 // 'http://example.tld/foo',129 // [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']130 // );131 var errorHandler = sinon.spy(function (error) {132 error.message.match(/timeout/);133 });134 var middlewareFn = function (error) {135 errorHandler.should.have.been.called;136 error.message.match(/timeout/);137 done();138 };139 api.register('bar', function (req, next) {140 next().catch(middlewareFn);141 });142 api.api.foo().catch(errorHandler);143 });144 });145 describe('configuration', function () {146 var api;147 var server;148 beforeEach(function () {149 api = superapi.default({150 baseUrl: 'http://example.tld',151 services: {152 foo: {153 path: 'foo'154 },155 bar: {156 path: 'bar',157 use: {158 tracker: false159 }160 }161 }162 });163 api.agent = superagent;164 // custom tracker header middleware165 api.register('tracker', function (req) {166 req.set('X-TRACKER-ID', 1234);167 });168 // add sinon to fake the XHR call169 server = sinon.fakeServer.create();170 });171 afterEach(function () {172 server.restore();173 server = null;174 api = null;175 });176 it('should execute tracker middleware', function (done) {177 // configure response178 server.respondWith('GET',179 'http://example.tld/foo',180 [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']181 );182 var spyMiddleware = sinon.spy(function (req) {183 req.header.should.have.property('X-TRACKER-ID', 1234);184 });185 api.register('spy', spyMiddleware);186 api.api.foo().then(function (res) {187 spyMiddleware.should.have.been.called;188 done();189 });190 server.respond();191 });192 it('should disable tracker middleware by setting `use: false`', function (done) {193 // configure response194 server.respondWith('GET',195 'http://example.tld/bar',196 [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']197 );198 var spyMiddleware = sinon.spy(function (req) {199 req.header.should.not.have.property('X-TRACKER-ID');200 });201 api.register('spy', spyMiddleware);202 api.api.bar().then(function (res) {203 spyMiddleware.should.have.been.called;204 done();205 });206 server.respond();207 });208 it('should not break everything if a middleware breaks', function (done) {209 // configure response210 server.respondWith('GET',211 'http://example.tld/bar',212 [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']213 );214 var spyMiddleware = sinon.spy(function (req) {215 throw new Error('boo!');216 });217 var thenSpy = sinon.spy(function () {});218 api.register('spy', spyMiddleware);219 api.api.foo()220 .then(thenSpy)221 .catch(function (err, res) {222 err.message.should.eql('boo!');223 224 thenSpy.should.not.have.been.called;225 spyMiddleware.should.been.called;226 done();227 });228 server.respond();229 });230 });231 describe('multiple middlewares', function () {232 var api;233 var server;234 beforeEach(function () {235 api = superapi.default({236 baseUrl: 'http://example.tld',237 services: {238 foo: {239 path: 'foo'240 },241 bar: {242 path: 'bar',243 use: {244 tracker: false245 }246 }247 }248 });249 api.agent = superagent;250 // custom middlewares251 api.register('foo', function (req) {252 req.set('foo', 'foo');253 });254 api.register('bar', function (req) {255 req.set('bar', 'bar');256 });257 // add sinon to fake the XHR call258 server = sinon.fakeServer.create();259 });260 afterEach(function () {261 server.restore();262 server = null;263 api = null;264 });265 it('should all be executed', function (done) {266 // configure response267 server.respondWith('GET',268 'http://example.tld/foo',269 [200, {'Content-Type': 'application/json'}, '{"result": "ok"}']270 );271 var spyMiddleware = sinon.spy(function (req) {272 req.header.should.have.property('foo', 'foo');273 req.header.should.have.property('bar', 'bar');274 });275 api.register('spy', spyMiddleware);276 api.api.foo().then(function (res) {277 spyMiddleware.should.have.been.called;278 done();279 });280 server.respond();281 });282 });283 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2mb.create({3}, function (error) {4 if (error) {5 console.error('Error creating mock server', error);6 } else {7 console.log('Mock server is up and running!');8 }9});10mb.create({11}, function (error) {12 if (error) {13 console.error('Error creating mock server', error);14 } else {15 console.log('Mock server is up and running!');16 }17});18var mb = require('mountebank');19mb.create({20}, function (error) {21 if (error) {22 console.error('Error creating mock server', error);23 } else {24 console.log('Mock server is up and running!');25 }26});27var mb = require('mountebank');28mb.create({29}, function (error) {30 if (error) {31 console.error('Error creating mock server', error);32 } else {33 console.log('Mock server is up and running!');34 }35});36var mb = require('mountebank');37mb.create({38}, function (error) {39 if (error) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var mountebank = require('mountebank');2var mb = mountebank.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto', ipWhitelist: ['*'] });3mb.start(function (error) {4 if (error) {5 console.error('Error starting mb', error);6 process.exit(1);7 }8 console.log('mb is up and running');9});10mb.post('/imposters', { protocol: 'http', port: 3000, stubs: [{ responses: [{ is: { body: 'Hello World' } }] }] }, function (error, response) {11 if (error) {12 console.error('Error creating imposter', error);13 process.exit(1);14 }15 console.log('imposter created');16});17mb.get('/imposters', function (error, response) {18 if (error) {19 console.error('Error retrieving imposters', error);20 process.exit(1);21 }22 console.log('imposters retrieved', response.body);23});24var mountebank = require('mountebank');25var mb = mountebank.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto', ipWhitelist: ['*'] });26mb.start(function (error) {27 if (error) {28 console.error('Error starting mb', error);29 process.exit(1);30 }31 console.log('mb is up and running');32});33mb.post('/imposters', { protocol: 'http', port: 3000, stubs: [{ responses: [{ is: { body: 'Hello World' } }] }] }, function (error, response) {34 if (error) {35 console.error('Error creating imposter', error);36 process.exit(1);37 }38 console.log('imposter created');39});40mb.get('/imposters', function (error, response) {41 if (error) {42 console.error('Error retrieving imposters', error);43 process.exit(1);44 }45 console.log('imposters retrieved', response.body);46});47var mountebank = require('mount

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const assert = require('assert');3mb.create({4}, function (error, server) {5 assert.ifError(error);6 console.log('Mountebank server started on port 2525');7});8mb.createImposter({9 {10 {11 is: {12 headers: {13 },14 body: JSON.stringify({15 })16 }17 }18 }19}, function (error, imposter) {20 assert.ifError(error);21 console.log('Imposter started on port 3000');22});23mb.createImposter({24 {25 {26 is: {27 headers: {28 },29 body: JSON.stringify({30 })31 }32 }33 }34}, function (error, imposter) {35 assert.ifError(error);36 console.log('Imposter started on port 3001');37});38mb.createImposter({39 {40 {41 is: {42 headers: {43 },44 body: JSON.stringify({45 })46 }47 }48 }49}, function (error, imposter) {50 assert.ifError(error);51 console.log('Imposter started on port 3002');52});53mb.createImposter({54 {55 {56 is: {57 headers: {58 },59 body: JSON.stringify({60 })61 }62 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const middlewareFn = require('mountebank').middleware;2const express = require('express');3const app = express();4const port = 3000;5app.use(middlewareFn);6app.listen(port, () => console.log(`Example app listening on port ${port}!`));7<% if (mb) { %>8<% } %>9<% if (mb) { %>10<% } %>11<?php if ($mb) { ?>12<?php } ?>13<?php if ($mb) { ?>14<?php } ?>15<?php if ($mb) { ?>16<?php } ?>17<?php if ($mb) { ?>18<?php } ?>19<?php if ($mb) { ?>20<?php } ?>21<?php if ($mb) { ?>22<?php } ?>23<?php if ($mb) { ?>

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var port = 2525;3var host = 'localhost';4var protocol = 'http';5var imposters = [{6 stubs: [{7 responses: [{8 is: {9 }10 }]11 }]12}];13mb.start({14}, function () {15 mb.createImposter(imposters, function (err, res) {16 console.log(res.body);17 });18});19var middlewareFn = function (req, res, next) {20 console.log(req.body);21 next();22};23mb.addMiddleware(url, middlewareFn, function (err, res) {24 console.log(res.body);25});26var mb = require('mountebank');27var port = 2525;28var host = 'localhost';29var protocol = 'http';30var imposters = [{31 stubs: [{32 responses: [{33 is: {34 }35 }]36 }]37}];38mb.start({39}, function () {40 mb.createImposter(imposters, function (err, res) {41 console.log(res.body);42 });43});44var middleware = {45 request: function (req, res, next) {46 console.log(req.body);47 next();48 }49};50mb.addMiddleware(url, middleware, function (err, res) {51 console.log(res.body);52});

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const port = 2525;3 {4 {5 {6 is: {7 headers: {8 },9 body: {10 }11 }12 }13 }14 }15];16mb.create({ port }, imposters).then(() => {17 console.log('Imposter created');18}).catch(error => {19 console.error('Error creating imposter', error);20});21const mb = require('mountebank');22const port = 2525;23 {24 {25 {26 is: {27 headers: {28 },29 body: {30 }31 }32 }33 }34 }35];36mb.create({ port }, imposters).then(() => {37 console.log('Imposter created');38}).catch(error => {39 console.error('Error creating imposter', error);40});41const mb = require('mountebank');42const port = 2525;43 {44 {45 {46 is: {47 headers: {48 },49 body: {50 }51 }52 }53 }54 }55];56mb.create({ port }, imposters).then(() => {57 console.log('Imposter created');58}).catch(error => {59 console.error('Error creating imposter', error);60});61const mb = require('mount

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const port = 2525;3const imposterPort = 3000;4const imposterProtocol = 'http';5const imposterName = 'imposter';6const imposterStub = {7 {8 is: {9 headers: {10 },11 body: JSON.stringify({12 })13 }14 }15};16const imposterPredicate = {17 equals: {18 }19};20mb.create({21}, () => {22 mb.post('/imposters', {23 }, () => {24 mb.post(`/imposters/${imposterPort}/predicates`, imposterPredicate, () => {25 mb.put(`/imposters/${imposterPort}/stubs/0`, {26 {27 is: {28 headers: {29 },30 body: JSON.stringify({31 })32 }33 }34 }, () => {35 console.log('stub updated');36 });37 });38 });39});40const mb = require('mountebank');41const port = 2525;42const imposterPort = 3000;43const imposterProtocol = 'http';44const imposterName = 'imposter';45const imposterStub = {46 {47 is: {48 headers: {49 },50 body: JSON.stringify({51 })52 }53 }54};55const imposterPredicate = {56 equals: {57 }58};59mb.create({

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const port = 2525;3const imposter = {4 {5 {6 is: {7 }8 }9 }10};11mb.create(port, imposter)12 .then(() => console.log('Imposter created successfully'))13 .catch(error => console.error(`Error creating imposter: ${error.message}`));14const middleware = {15 {16 {17 is: {18 }19 }20 }21 _links: {22 self: {23 }24 }25};26mb.addMiddleware(port, 8080, middleware)27 .then(() => console.log('Middleware added successfully'))28 .catch(error => console.error(`Error adding middleware: ${error.message}`));29mb.removeMiddleware(port, 8080, 'myMiddleware')30 .then(() => console.log('Middleware removed successfully'))31 .catch(error => console.error(`Error removing middleware: ${error.message}`));32mb.del(port, 8080)33 .then(() => console.log('Imposter deleted successfully'))34 .catch(error => console.error(`Error deleting imposter: ${error.message}`));35mb.verify(port, 8080)36 .then(() => console.log('Imposter verified successfully'))37 .catch(error => console.error(`Error verifying imposter: ${error.message}`));38mb.get(port)39 .then(imposters => console.log(`Imposters: ${JSON.stringify(imposters)}`))40 .catch(error => console.error(`Error getting imposters: ${error.message}`));41mb.get(port, 8080)42 .then(imposter => console.log(`Imposter: ${JSON.stringify(imposter)}`))

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