Best JavaScript code snippet using mountebank
transpile.js
Source:transpile.js
1module.exports = function (grunt) {2 var esperanto = require('esperanto');3 var path = require('path');4 var Promise = require('es6-promise').Promise;5 var TMP_DIR = 'build/tmp';6 function moveComments(code) {7 var comments = [], rest = [];8 code.split('\n').forEach(function (line) {9 if (line.trim().slice(0, 3) === '//!') {10 comments.push(line.trim());11 } else {12 rest.push(line);13 }14 });15 return comments.concat([''], rest).join('\n');16 }17 var headerCache = {};18 function getHeaderByFile(headerFile) {19 if (!(headerFile in headerCache)) {20 headerCache[headerFile] = grunt.file.read(headerFile);21 }22 return headerCache[headerFile];23 }24 function transpile(opts) {25 // base, entry, skip, headerFile, skipLines, target26 var umdName = opts.headerFile ? 'not_used' : opts.umdName,27 headerFile = opts.headerFile ? opts.headerFile : 'templates/default.js',28 header = getHeaderByFile(headerFile),29 skipLines = opts.skipLines ? opts.skipLines : 5;30 return esperanto.bundle({31 base: opts.base,32 entry: opts.entry,33 skip: opts.skip || []34 }).then(function (bundle) {35 var umd = bundle.toUmd({name: umdName}),36 fixed = header + umd.code.split('\n').slice(skipLines).join('\n');37 if (opts.moveComments) {38 fixed = moveComments(fixed);39 }40 grunt.file.write(opts.target, fixed);41 });42 }43 function transpileMany(opts) {44 var batchSize = 50,45 promise = Promise.resolve(null),46 files = grunt.file.expand({cwd: opts.base}, opts.pattern),47 i,48 transpileOne = function (i) {49 promise = promise.then(function () {50 return Promise.all(files.slice(i, i + batchSize).map(function (file) {51 return transpile({52 base: opts.base,53 entry: file,54 headerFile: opts.headerFile,55 skip: opts.skip,56 skipLines: opts.skipLines,57 moveComments: opts.moveComments,58 target: path.join(opts.targetDir, file)59 });60 }));61 });62 };63 for (i = 0; i < files.length; i += batchSize) {64 transpileOne(i);65 }66 return promise;67 }68 function prepareTemp(base) {69 var files = grunt.file.expand({cwd: base}, '**/*.js'),70 tmpDir = TMP_DIR;71 if (grunt.file.exists(tmpDir)) {72 return;73 }74 files.forEach(function (file) {75 grunt.file.copy(path.join(base, file), path.join(tmpDir, file));76 });77 }78 function transpileCode(opts) {79 var entry = opts.entry || path.basename(opts.target);80 prepareTemp(opts.base);81 grunt.file.write(path.join(TMP_DIR, entry), opts.code);82 return transpile({83 base: TMP_DIR,84 entry: entry,85 umdName: opts.umdName || 'not_used',86 headerFile: opts.headerFile,87 skipLines: opts.skipLines,88 moveComments: opts.moveComments,89 target: opts.target,90 skip: opts.skip91 });92 }93 function generateLocales(target, localeFiles) {94 var files = localeFiles,95 code = files.map(function (file) {96 var identifier = path.basename(file, '.js').replace('-', '_');97 return 'import ' + identifier + ' from "./' + file + '";';98 }).concat([99 // Reset the language back to 'en', because every defineLocale100 // also sets it.101 'moment.locale(\'en\');'102 ]).join('\n');103 return transpileCode({104 base: 'src',105 code: code,106 target: target,107 skip: ['moment'],108 headerFile: 'templates/locale-header.js',109 skipLines: 5110 });111 }112 function generateMomentWithLocales(target, localeFiles) {113 var files = localeFiles,114 importCode = files.map(function (file) {115 var identifier = path.basename(file, '.js').replace('-', '_');116 var fileNoExt = file.replace('.js', '');117 return 'import ' + identifier + ' from "./' + fileNoExt + '";';118 }).join('\n'),119 code = 'import * as moment_export from "./moment";\n\n' +120 importCode + '\n\n' +121 'export default moment_export;';122 return transpileCode({123 base: 'src',124 code: code,125 umdName: 'moment',126 target: target127 }).then(function () {128 var code = grunt.file.read(target);129 var getDefaultRegExp = new RegExp('var ([a-z$_]+) =\\s+{[^]\\s+get default \\(\\) { return ([a-z$_]+); }[^]\\s+}', '');130 var crap = code.match(getDefaultRegExp);131 if (crap.length !== 3) {132 grunt.file.write('/tmp/crap.js', code);133 throw new Error('Failed to detect get default crap, check /tmp/crap.js');134 }135 code = code.replace(getDefaultRegExp, '');136 var buildExportVars = ['moment_with_locales', 'moment_with_locales_custom'];137 buildExportVars.forEach(function (buildExportVar) {138 var languageReset = buildExportVar + '.locale(\'en\');';139 code = code.replace('var ' + buildExportVar + ' = ' + crap[1] + ';',140 'var ' + buildExportVar + ' = ' + crap[2] + ';\n' +141 ' ' + languageReset);142 });143 if (code.match('get default')) {144 grunt.file.write('/tmp/crap.js', code);145 throw new Error('Stupid shit es6 get default plaguing the code, check /tmp/crap.js');146 }147 grunt.file.write(target, code);148 });149 }150 grunt.task.registerTask('transpile-raw', 'convert es6 to umd', function () {151 var done = this.async();152 transpile({153 base: 'src',154 entry: 'moment.js',155 umdName: 'moment',156 target: 'build/umd/moment.js',157 moveComments: true158 }).then(function () {159 grunt.log.ok('build/umd/moment.js');160 }).then(function () {161 return transpileMany({162 base: 'src',163 pattern: 'locale/*.js',164 headerFile: 'templates/locale-header.js',165 skipLines: 5,166 moveComments: true,167 targetDir: 'build/umd',168 skip: ['moment']169 });170 }).then(function () {171 grunt.log.ok('build/umd/locale/*.js');172 }).then(function () {173 return transpileMany({174 base: 'src',175 pattern: 'test/moment/*.js',176 headerFile: 'templates/test-header.js',177 skipLines: 5,178 moveComments: true,179 targetDir: 'build/umd',180 skip: ['moment']181 });182 }).then(function () {183 grunt.log.ok('build/umd/test/moment/*.js');184 }).then(function () {185 return transpileMany({186 base: 'src',187 pattern: 'test/locale/*.js',188 headerFile: 'templates/test-header.js',189 skipLines: 5,190 moveComments: true,191 targetDir: 'build/umd',192 skip: ['moment']193 });194 }).then(function () {195 grunt.log.ok('build/umd/test/locale/*.js');196 }).then(function () {197 return generateLocales('build/umd/min/locales.js',198 grunt.file.expand({cwd: 'src'}, 'locale/*.js'));199 }).then(function () {200 grunt.log.ok('build/umd/min/locales.js');201 }).then(function () {202 return generateMomentWithLocales('build/umd/min/moment-with-locales.js',203 grunt.file.expand({cwd: 'src'}, 'locale/*.js'));204 }).then(function () {205 grunt.log.ok('build/umd/min/moment-with-locales.js');206 }).then(done, function (e) {207 grunt.log.error('error transpiling', e);208 done(e);209 });210 });211 grunt.task.registerTask('transpile-custom-raw',212 'build just custom language bundles',213 function (locales) {214 var done = this.async();215 var localeFiles = locales.split(',').map(function (locale) {216 var file = grunt.file.expand({cwd: 'src'}, 'locale/' + locale + '.js');217 if (file.length !== 1) {218 // we failed to find a locale219 done(new Error('could not find locale: ' + locale));220 done = null;221 } else {222 return file[0];223 }224 });225 // There was an issue with a locale226 if (done == null) {227 return;228 }229 return generateLocales(230 'build/umd/min/locales.custom.js', localeFiles231 ).then(function () {232 grunt.log.ok('build/umd/min/locales.custom.js');233 }).then(function () {234 return generateMomentWithLocales('build/umd/min/moment-with-locales.custom.js',235 localeFiles);236 }).then(function () {237 grunt.log.ok('build/umd/min/moment-with-locales.custom.js');238 }).then(done, function (e) {239 grunt.log.error('error transpiling-custom', e);240 done(e);241 });242 });243 grunt.config('clean.build', [244 'build'245 ]);246 grunt.config('concat.tests', {247 src: 'build/umd/test/**/*.js',248 dest: 'build/umd/min/tests.js'249 });250 grunt.task.registerTask('transpile',251 'builds all es5 files, optinally creating custom locales',252 function (locales) {253 var tasks = [254 'clean:build',255 'transpile-raw',256 'concat:tests'257 ];258 if (locales) {259 tasks.push('transpile-custom-raw:' + locales);260 }261 grunt.task.run(tasks);262 });...
Using AI Code Generation
1var imposter = {2 {3 {4 "is": {5 "headers": {6 },7 }8 }9 }10};11var headerFile = {12 {13 {14 "is": {15 "headers": {16 },17 }18 }19 }20};21var mb = require('mountebank');22mb.create(imposter, function (error, imposter) {23 if (error) {24 console.error('Error creating imposter', error);25 } else {26 console.log('Created imposter', imposter.port);27 }28});29mb.create(headerFile, function (error, imposter) {30 if (error) {31 console.error('Error creating imposter', error);32 } else {33 console.log('Created imposter', imposter.port);34 }35});36mb.get('/redirect', function (request, response) {37 response.statusCode = 200;38 response.end('Redirected!');39});40mb.start(2525, function (error) {41 if (error) {42 console.error('Error starting mountebank', error);43 } else {44 console.log('Mountebank started');45 }46});47mb.stop(function (error) {48 if (error) {49 console.error('Error stopping mountebank', error);50 } else {51 console.log('Mountebank stopped');52 }53});54mb.del(imposter.port, function (error) {55 if (error) {56 console.error('Error deleting imposter', error);57 } else {58 console.log('Deleted imposter', imposter.port);59 }60});61mb.del(headerFile.port, function (error) {62 if (error) {63 console.error('Error deleting imposter', error);64 } else {65 console.log('Deleted imposter', headerFile.port);66 }67});68mb.get('/redirect', function
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var imposter = {4 {5 {6 is: {7 headers: {8 },9 body: '{"status":"ok"}'10 }11 }12 }13};14mb.create({port: port, allowInjection: true}, function () {15 mb.post('/imposters', imposter, function () {16 console.log('Imposter created');17 });18});19var mb = require('mountebank');20var port = 2525;21var imposter = {22 {23 {24 is: {25 headers: {26 },27 body: '{"status":"ok"}'28 }29 }30 }31};32mb.create({port: port, allowInjection: true}, function () {33 mb.post('/imposters', imposter, function () {34 console.log('Imposter created');35 });36});37var mb = require('mountebank');38var port = 2525;39var imposter = {40 {41 {42 is: {43 headers: {44 },45 body: '{"status":"ok"}'46 }47 }48 }49};50mb.create({port: port, allowInjection: true}, function () {51 mb.post('/imposters', imposter, function () {52 console.log('Imposter created');53 });54});55var mb = require('mountebank');56var port = 2525;57var imposter = {58 {59 {60 is: {
Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create({3 {4 {5 equals: {6 }7 }8 {9 is: {10 headers: {11 },12 body: {13 }14 }15 }16 }17});18imposter.then(function (imposter) {19 console.log('imposter running at port ' + imposter.port);20});21imposter.then(function (imposter) {22 return imposter.get('/test');23}).then(function (response) {24 console.log(response.statusCode);25 console.log(response.body);26});27var mb = require('mountebank');28var imposter = mb.create({29 {30 {31 equals: {32 }33 }34 {35 is: {36 headers: {37 },38 body: {39 }40 }41 }42 }43});44imposter.then(function (imposter) {45 console.log('imposter running at port ' + imposter.port);46});47imposter.then(function (imposter) {48 return imposter.get('/test');49}).then(function (response) {50 console.log(response.statusCode);51 console.log(response.body);52});53var mb = require('mountebank');54var imposter = mb.create({55 {56 {57 equals: {58 }59 }60 {61 is: {62 headers: {63 },64 body: {65 }
Using AI Code Generation
1var assert = require('assert');2var mb = require('mountebank');3mb.start({4}, function (error) {5 assert.ifError(error);6 mb.post('/imposters', {7 {8 {9 is: {10 headers: {11 },12 body: JSON.stringify({ hello: 'world' })13 }14 }15 }16 }, function (error, response) {17 assert.ifError(error);18 assert.strictEqual(response.statusCode, 201);19 mb.get('/hello', { headers: { 'Accept': 'application/json' } }, function (error, response) {20 assert.ifError(error);21 assert.strictEqual(response.statusCode, 200);22 assert.strictEqual(response.body, { hello: 'world' });23 assert.strictEqual(response.headers['content-type'], 'application/json');24 assert.strictEqual(response.headers['access-control-allow-origin'], '*');25 mb.stop(function (error) {26 assert.ifError(error);27 });28 });29 });30});
Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create({3 {4 {5 is: {6 headers: {7 },8 }9 }10 }11});12imposter.then(function (server) {13 console.log('running at port 2525');14 server.close();15});16var mb = require('mountebank');17var imposter = mb.create({18 {19 {20 is: {21 headers: {22 },23 }24 }25 }26});27imposter.then(function (server) {28 console.log('running at port 2525');29 server.close();30});31var mb = require('mountebank');32var imposter = mb.create({33 {34 {35 is: {36 headers: {37 },38 }39 }40 }41});42imposter.then(function (server) {43 console.log('running at port 2525');44 server.close();45});
Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create({port: 2525, name: 'MyImposter'});3imposter.post('/test', function (request, response) {4 response({statusCode: 200, body: 'Hello World!'});5});6imposter.run();7var mb = require('mountebank');8var imposter = mb.create({port: 2525, name: 'MyImposter'});9imposter.post('/test', function (request, response) {10 response({statusCode: 200, body: 'Hello World!'});11});12imposter.run();13var mb = require('mountebank');14var imposter = mb.create({port: 2525, name: 'MyImposter'});15imposter.post('/test', function (request, response) {16 response({statusCode: 200, body: 'Hello World!'});17});18imposter.run();19var mb = require('mountebank');20var imposter = mb.create({port: 2525, name: 'MyImposter'});21imposter.post('/test', function (request, response) {22 response({statusCode: 200, body: 'Hello World!'});23});24imposter.run();25var mb = require('mountebank');26var imposter = mb.create({port: 2525, name: 'MyImposter'});27imposter.post('/test', function (request, response) {28 response({statusCode: 200, body: 'Hello World!'});29});30imposter.run();31var mb = require('mountebank');32var imposter = mb.create({port: 2525, name: 'MyImposter'});33imposter.post('/test', function (request, response) {34 response({statusCode: 200, body: 'Hello World!'});35});36imposter.run();37var mb = require('mountebank');38var imposter = mb.create({port: 2525, name: 'MyImposter'});39imposter.post('/test', function (request, response) {40 response({statusCode: 200, body: 'Hello
Using AI Code Generation
1var mb = require('mountebank'),2 assert = require('assert');3 stub = {4 {5 is: {6 }7 }8 },9 mb = mb.create(port);10mb.start().then(function () {11 return mb.post('/imposters', { protocol: 'http', port: 3000, stubs: [stub] });12}).then(function (response) {13 var url = response.headers.location;14 return mb.get(url);15}).then(function (response) {16 assert.equal(response.body, 'Hello world!');17 return mb.del('/imposters');18}).then(function () {19 return mb.stop();20}).done();21 throw e;22 at createHangUpError (_http_client.js:215:15)23 at Socket.socketCloseListener (_http_client.js:247:23)24 at emitOne (events.js:77:13)25 at Socket.emit (events.js:169:7)26 at TCP._onclose (net.js:469:12)27The problem is that the server is not running when you call mb.start() . This is because the mb.start() method returns a promise that resolves when the server is ready, but you don't wait for that promise to resolve before calling mb.post() . If you want to use the promise returned by mb.start() , you need to do something like this:28mb.start().then(function () {29 return mb.post('/imposters', { protocol: 'http', port: 3000, stubs: [stub] });30}).then(function (response) {31 var url = response.headers.location;32 return mb.get(url);33}).then(function (response) {34 assert.equal(response.body, 'Hello
Using AI Code Generation
1var mb = require('mountebank');2var fs = require('fs');3var imposter = {4 stubs: [{5 responses: [{6 is: {7 headers: {8 },9 body: fs.readFileSync('response.json').toString()10 }11 }]12 }]13};14mb.create(imposter).then(function () {15 console.log('Imposter created');16});17{18}19var mb = require('mountebank');20var fs = require('fs');21var imposter = {22 stubs: [{23 responses: [{24 is: {25 headers: {26 },27 body: fs.readFileSync('response.json').toString()28 }29 }]30 }]31};32mb.create(imposter).then(function () {33 console.log('Imposter created');34});35{36}37var mb = require('mountebank');38var fs = require('fs');39var imposter = {40 stubs: [{
Using AI Code Generation
1var mb = require('mountebank');2var fs = require('fs');3var port = 2525;4var host = 'localhost';5var imposterPort = 4545;6var imposterName = 'testImposter';7var imposterProtocol = 'http';8var imposterStub = {9 {10 is: {11 headers: {12 },13 body: fs.readFileSync('response.json', 'utf8')14 }15 }16};17var imposter = {18};19mb.create({20}, function (error, imposter) {21 if (error) {22 console.error('Failed to create mountebank with error: ' + error);23 } else {24 imposter.post('/imposters', imposter, function (error, response) {25 if (error) {26 console.error('Failed to create imposter with error: ' + error);27 } else {28 console.log('Imposter created successfully');29 }30 });31 }32});
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!!