How to use defaultIEtoHTML method in mountebank

Best JavaScript code snippet using mountebank

middleware.js

Source:middleware.js Github

copy

Full Screen

1'use strict';2/**3 * Express middleware functions to inject into the HTTP processing4 * @module5 */6var errors = require('./errors');7/**8 * Returns a middleware function to transforms all outgoing relative links in the response body9 * to absolute URLs, incorporating the current host name and port10 * @param {number} port - The port of the current instance11 * @returns {Function}12 */13function useAbsoluteUrls (port) {14 return function (request, response, next) {15 var setHeaderOriginal = response.setHeader,16 sendOriginal = response.send,17 host = request.headers.host || 'localhost:' + port,18 absolutize = function (link) { return 'http://' + host + link; };19 response.setHeader = function () {20 var args = Array.prototype.slice.call(arguments);21 if (args[0] && args[0].toLowerCase() === 'location') {22 args[1] = absolutize(args[1]);23 }24 setHeaderOriginal.apply(this, args);25 };26 response.send = function () {27 var args = Array.prototype.slice.call(arguments),28 body = args[0],29 changeLinks = function (obj) {30 if (obj._links) {31 Object.keys(obj._links).forEach(function (rel) {32 obj._links[rel].href = absolutize(obj._links[rel].href);33 });34 }35 },36 traverse = function (obj, fn) {37 fn(obj);38 Object.keys(obj).forEach(function (key) {39 if (obj[key] && typeof obj[key] === 'object') {40 traverse(obj[key], fn);41 }42 });43 };44 if (typeof body === 'object') {45 traverse(body, changeLinks);46 }47 sendOriginal.apply(this, args);48 };49 next();50 };51}52/**53 * Returns a middleware function to return a 404 if the imposter does not exist54 * @param {Object} imposters - The current dictionary of imposters55 * @returns {Function}56 */57function createImposterValidator (imposters) {58 return function validateImposterExists (request, response, next) {59 var imposter = imposters[request.params.id];60 if (imposter) {61 next();62 }63 else {64 response.statusCode = 404;65 response.send({66 errors: [errors.MissingResourceError('Try POSTing to /imposters first?')]67 });68 }69 };70}71/**72 * Returns a middleware function that logs the requests made to the server73 * @param {Object} log - The logger74 * @param {string} format - The log format75 * @returns {Function}76 */77function logger (log, format) {78 function shouldLog (request) {79 var isStaticAsset = (['.js', '.css', '.gif', '.png', '.ico'].some(function (fileType) {80 return request.url.indexOf(fileType) >= 0;81 })),82 isHtmlRequest = (request.headers.accept || '').indexOf('html') >= 0,83 isXHR = request.headers['x-requested-with'] === 'XMLHttpRequest';84 return !(isStaticAsset || isHtmlRequest || isXHR);85 }86 return function (request, response, next) {87 if (shouldLog(request)) {88 var message = format.replace(':method', request.method).replace(':url', request.url);89 log.info(message);90 }91 next();92 };93}94/**95 * Returns a middleware function that passes global variables to all render calls without96 * having to pass them explicitly97 * @param {Object} vars - the global variables to pass98 * @returns {Function}99 */100function globals (vars) {101 return function (request, response, next) {102 var originalRender = response.render;103 response.render = function () {104 var args = Array.prototype.slice.call(arguments),105 variables = args[1] || {};106 Object.keys(vars).forEach(function (name) {107 variables[name] = vars[name];108 });109 args[1] = variables;110 originalRender.apply(this, args);111 };112 next();113 };114}115/**116 * The mountebank server uses header-based content negotiation to return either HTML or JSON117 * for each URL. This breaks down on IE browsers as they fail to send the correct Accept header,118 * and since we default to JSON (to make the API easier to use), that leads to a poor experience119 * for IE users. We special case IE to html by inspecting the user agent, making sure not to120 * interfere with XHR requests that do add the Accept header121 * @param {Object} request - The http request122 * @param {Object} response - The http response123 * @param {Function} next - The next middleware function to call124 */125function defaultIEtoHTML (request, response, next) {126 // IE has inconsistent Accept headers, often defaulting to */*127 // Our default is JSON, which fails to render in the browser on content-negotiated pages128 if (request.headers['user-agent'] && request.headers['user-agent'].indexOf('MSIE') >= 0) {129 if (!(request.headers.accept && request.headers.accept.match(/application\/json/))) {130 request.headers.accept = 'text/html';131 }132 }133 next();134}135/**136 * Returns a middleware function that defaults the content type to JSON if not set to make137 * command line testing easier (e.g. you don't have to set the Accept header with curl) and138 * parses the JSON before reaching a controller, handling errors gracefully.139 * @param {Object} log - The logger140 * @returns {Function}141 */142function json (log) {143 return function (request, response, next) {144 request.body = '';145 request.setEncoding('utf8');146 request.on('data', function (chunk) {147 request.body += chunk;148 });149 request.on('end', function () {150 if (request.body === '') {151 next();152 }153 else {154 try {155 request.body = JSON.parse(request.body);156 request.headers['content-type'] = 'application/json';157 next();158 }159 catch (e) {160 log.error('Invalid JSON: ' + request.body);161 response.statusCode = 400;162 response.send({163 errors: [errors.InvalidJSONError({ source: request.body })]164 });165 }166 }167 });168 };169}170module.exports = {171 useAbsoluteUrls: useAbsoluteUrls,172 createImposterValidator: createImposterValidator,173 logger: logger,174 globals: globals,175 defaultIEtoHTML: defaultIEtoHTML,176 json: json...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var fs = require('fs');3var path = require('path');4var imposter = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'imposter.json'), 'utf8'));5var options = {6};7mb.create(options, function (error, mbServer) {8 if (error) {9 console.log('Error while starting mountebank', error);10 } else {11 mbServer.defaultIEtoHTML(imposter, function (error, response) {12 if (error) {13 console.log('Error while creating imposter', error);14 } else {15 console.log('Imposter created successfully', response);16 }17 });18 }19});20{21 {22 {23 "is": {24 "headers": {25 },26 }27 }28 }29}

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2mb.defaultIEtoHTML();3var server = mb.create({4});5var stub = {6 {7 equals: {8 }9 }10 {11 is: {12 }13 }14};15var mock = {16};17server.then(function (server) {18 server.createMock(mock);19});20var request = {21};22server.then(function (server) {23 server.send(request).then(function (response) {24 console.log(response);25 });26});27server.then(function (server) {28 server.verify().then(function (result) {29 console.log(result);30 });31});32server.then(function (server) {33 server.deleteMock(2526);34});35server.then(function (server) {36 server.stop();37});38var stub = {39 {40 equals: {41 }42 }43 {44 is: {45 }46 }47};48var mock = {49};50server.then(function (server) {51 server.createMock(mock);52});53var request = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposters = { "imposters" : [ {3 "stubs" : [ {4 "responses" : [ {5 "is" : {6 }7 } ]8 } ]9} ] };10mb.create({ "port" : 2525, "pidfile" : "mb.pid", "logfile" : "mb.log" }, function() {11 mb.post("/imposters", imposters, function() {12 mb.get("/imposters/8080", function(response) {13 console.log(response.body);14 mb.delete("/imposters/8080", function() {15 mb.get("/imposters/8080", function(response) {16 console.log(response.body);17 mb.delete("/imposters", function() {18 mb.get("/imposters", function(response) {19 console.log(response.body);20 mb.stop();21 });22 });23 });24 });25 });26 });27});28var mb = require('mountebank');29var imposters = { "imposters" : [ {30 "stubs" : [ {31 "responses" : [ {32 "is" : {33 }34 } ]35 } ]36} ] };37mb.create({ "port" : 2525, "pidfile" : "mb.pid", "logfile" : "mb.log" }, function() {38 mb.post("/imposters", imposters, function() {39 mb.get("/imposters/8080", function(response) {40 console.log(response.body);41 mb.delete("/imposters/8080", function() {42 mb.get("/imposters/8080", function(response) {43 console.log(response.body);44 mb.delete("/imposters", function() {45 mb.get("/imposters", function(response) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposters = mb.create({port:2525, pidfile:'mb.pid', logfile:'mb.log'});3imposters.create({protocol: 'http', port: 3000, stubs: [{responses: [{is: {body: 'Hello World'}}]}]})4.then(function () {5console.log('Imposter created');6});7var mb = require('mountebank');8var imposters = mb.create({port:2525, pidfile:'mb.pid', logfile:'mb.log'});9imposters.create({protocol: 'http', port: 3000, stubs: [{responses: [{is: {body: 'Hello World'}}]}]})10.then(function () {11console.log('Imposter created');12});13throw new Error('Unable to create log file: ' + filename + ' ' + e);14at Object.fs.openSync (fs.js:439:18)15at Object.fs.writeFileSync (fs.js:978:15)16at Object.fs.appendFileSync (fs.js:1019:6)17at Object. (C:\Users\abc\Documents\mountebank18at Module._compile (module.js:456:26)19at Object.Module._extensions..js (module.js:474:10)20at Module.load (module.js:356:32)21at Function.Module._load (module.js:312:12)22at Module.require (module.js:364:17)23at require (module.js:380:17)24var mb = require('mountebank');25var imposters = mb.create({port:2525, pidfile:'mb.pid', logfile:'mb.log'});26imposters.create({

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2mb.defaultIEtoHTML(3000);3const mb = require('mountebank');4mb.defaultIEtoHTML(3001);5const mb = require('mountebank');6mb.defaultIEtoHTML(3002);7const mb = require('mountebank');8mb.defaultIEtoHTML(3003);9const mb = require('mountebank');10mb.defaultIEtoHTML(3004);11const mb = require('mountebank');12mb.defaultIEtoHTML(3005);13const mb = require('mountebank');14mb.defaultIEtoHTML(3006);15const mb = require('mountebank');16mb.defaultIEtoHTML(3007

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2const mb = require('mountebank');3const port = 2525;4const protocol = 'http';5 {6 {7 equals: {8 },9 },10 {11 is: {12 headers: {13 },14 },15 },16 },17];18mb.create({19})20 .then(() => mb.stub({ protocol, port, stubs }))21 .then(() => mb.get({ protocol, port, path: '/' }))22 .then(response => {23 assert.strictEqual(response.statusCode, 200);24 assert.strictEqual(response.body, '<html><body><h1>Test</h1></body></html>');25 assert.strictEqual(response.headers['content-type'], 'text/html');26 console.log('Success!');27 })28 .finally(() => mb.stop({ port }));29{ statusCode: 200,30 { 'content-type': 'application/json',31 'content-length': '44' },32 body: '{"statusCode":200,"headers":{},"body":""}' }33var imposter = {34 {35 {36 equals: {37 }38 }39 {40 is: {

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