Best JavaScript code snippet using mountebank
service-worker.js
Source:service-worker.js
1import { timestamp, files, shell } from '@sapper/service-worker';2const ASSETS = `cache${timestamp}`;3// `shell` is an array of all the files generated by the bundler,4// `files` is an array of everything in the `static` directory5const to_cache = shell.concat(files);6const staticAssets = new Set(to_cache);7self.addEventListener('install', event => {8 event.waitUntil(9 caches10 .open(ASSETS)11 .then(cache => cache.addAll(to_cache))12 .then(() => {13 self.skipWaiting();14 })15 );16});17self.addEventListener('activate', event => {18 event.waitUntil(19 caches.keys().then(async keys => {20 // delete old caches21 for (const key of keys) {22 if (key !== ASSETS) await caches.delete(key);23 }24 self.clients.claim();25 })26 );27});28/**29 * Fetch the asset from the network and store it in the cache. 30 * Fall back to the cache if the user is offline.31 */32async function fetchAndCache(request) {33 const cache = await caches.open(`offline${timestamp}`)34 try {35 const response = await fetch(request);36 cache.put(request, response.clone());37 return response;38 } catch (err) {39 const response = await cache.match(request);40 if (response) return response;41 throw err;42 }43}44self.addEventListener('fetch', event => {45 if (event.request.method !== 'GET' || event.request.headers.has('range')) return;46 const url = new URL(event.request.url);47 // don't try to handle e.g. data: URIs48 const isHttp = url.protocol.startsWith('http');49 const isDevServerRequest = url.hostname === self.location.hostname && url.port !== self.location.port;50 const isStaticAsset = url.host === self.location.host && staticAssets.has(url.pathname);51 const skipBecauseUncached = event.request.cache === 'only-if-cached' && !isStaticAsset;52 if (isHttp && !isDevServerRequest && !skipBecauseUncached) {53 event.respondWith(54 (async () => {55 // always serve static files and bundler-generated assets from cache.56 // if your application has other URLs with data that will never change,57 // set this variable to true for them and they will only be fetched once.58 const cachedAsset = isStaticAsset && await caches.match(event.request);59 // for pages, you might want to serve a shell `service-worker-index.html` file,60 // which Sapper has generated for you. It's not right for every61 // app, but if it's right for yours then uncomment this section62 /*63 if (!cachedAsset && url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {64 return caches.match('/service-worker-index.html');65 }66 */67 return cachedAsset || fetchAndCache(event.request);68 })()69 );70 }...
is-static-asset.js
Source:is-static-asset.js
1var assert = require('assert');2var isStaticAsset = require('../lib/is-static-asset');3require('dash-assert');4describe('isStaticAsset', function() {5 it('anyExceptHtml', function() {6 assert.isTrue(isStaticAsset.anyExceptHtml({path: '/js/main.js'}));7 assert.isTrue(isStaticAsset.anyExceptHtml({path: '/img/logo.png'}));8 assert.isTrue(isStaticAsset.anyExceptHtml({path: '/img/logo.jpg'}));9 assert.isFalse(isStaticAsset.anyExceptHtml({path: '/templates/home.html'}));10 assert.isFalse(isStaticAsset.anyExceptHtml({path: '/'}));11 assert.isFalse(isStaticAsset.anyExceptHtml({path: '/blog'}));12 });13 it('html', function() {14 assert.isTrue(isStaticAsset.html({path: '/templates/home.html'}));15 assert.isFalse(isStaticAsset.html({path: '/js/main.js'}));16 });17 it('image', function() {18 assert.isTrue(isStaticAsset.image({path: '/images/photo.png'}));19 assert.isTrue(isStaticAsset.image({path: '/images/profile.jpg'}));20 assert.isFalse(isStaticAsset.image({path: '/js/main.js'}));21 });22 it('htmlXhr', function() {23 assert.isFalse(isStaticAsset.htmlXhr({path: '/templates/home.html'}));24 assert.isTrue(isStaticAsset.htmlXhr({path: '/templates/home.html', xhr: true}));25 });26 it('htmlNotXhr', function() {27 assert.isTrue(isStaticAsset.htmlNotXhr({path: '/templates/home.html'}));28 assert.isFalse(isStaticAsset.htmlNotXhr({path: '/templates/home.html', xhr: true}));29 });...
Using AI Code Generation
1const mb = require('mountebank');2const path = require('path');3const fs = require('fs');4 {5 {6 {7 equals: {8 }9 }10 {11 is: {12 }13 }14 },15 {16 {17 equals: {18 }19 }20 {21 is: {22 }23 }24 }25 }26];27mb.create({ port: 2525, pidfile: 'mb.pid', logfile: 'mb.log' }, () => {28 mb.startServer({ imposters }, () => {29 console.log('Imposter created!');30 console.log('Run `mb stop` to shutdown');31 });32});
Using AI Code Generation
1const mb = require('mountebank');2const fs = require('fs');3const path = require('path');4const port = 2525;5const protocol = 'http';6const host = 'localhost';7const impostor = {8 {9 {10 is: {11 }12 }13 }14};15const predicate = {16 { equals: { method: 'GET' } },17 { startsWith: { path: '/test' } },18 { isStaticAsset: { path: path.resolve('static') } }19};20impostor.stubs[0].predicates = [predicate];21const server = mb.create({22});23server.then(() => {24 return mb.post(url, impostor);25}).then(() => {26 return mb.get(`${url}/test`);27}).then(response => {28}).then(() => {29 return mb.get(`${url}/test/static/test.txt`);30}).then(response => {31}).then(() => {32 return mb.get(`${url}/test/static/doesnotexist.txt`);33}).then(response => {34}).then(() => {35 return mb.get(`${url}/test/doesnotexist.txt`);36}).then(response => {37}).then(() => {38 return mb.get(`${url}/doesnotexist`);39}).then(response => {40}).then(()
Using AI Code Generation
1var mbHelper = require('mountebank-helper');2var mb = mbHelper.create({ port: 2525, pidfile: 'mb.pid' });3});4### create(options)5* `port`: the port on which mountebank is running (default: 2525)6* `pidfile`: the path to the pidfile created by mountebank (default: mb.pid)7* `allowInjection`: whether to allow injection of JavaScript into responses (default: false)8* `localOnly`: whether to only allow the current machine to access the imposters (default: true)9* `debug`: whether to log debug information (default: false)10* `logfile`: the path to the logfile to use (default: mb.log)11* `protofile`: the path to the protofile to use (default: mb.proto)12* `ipWhitelist`: an array of IPs to allow access to the imposters (default: [])13* `defaultMode`: the default mode to use for imposters (default: text)14* `loglevel`: the loglevel to use (default: info)15* `loglevelFile`: the loglevel to use for the logfile (default: info)16* `nodepath`: the path to the node executable (default: /usr/local/bin/node)17* `nodeOptions`: the options to pass to node (default: [])18* `mbpath`: the path to the mountebank executable (default: /usr/local/bin/mb)19* `mbOptions`: the options to pass to mountebank (default: [])20* `timeout`: the timeout for mb start (default: 10000)21### start(callback)22### stop(callback)23### isRunning(callback)24### createImposter(options, callback)
Using AI Code Generation
1const mb = require('mountebank');2const fs = require('fs');3const path = require('path');4const config = require('./config');5const port = config.port;6const protocol = config.protocol;7const host = config.host;8const imposterPath = config.imposterPath;9const imposters = config.imposters;10const imposterPort = config.imposterPort;11const imposterProtocol = config.imposterProtocol;12const imposterHost = config.imposterHost;13const imposterName = config.imposterName;14const imposterStubPath = config.imposterStubPath;15const imposterStubResponsePath = config.imposterStubResponsePath;16const imposterStubResponseFile = config.imposterStubResponseFile;17const imposterStubResponseHeaders = config.imposterStubResponseHeaders;18const imposterStubPredicatesPath = config.imposterStubPredicatesPath;19const imposterStubPredicatesEqualsPath = config.imposterStubPredicatesEqualsPath;20const imposterStubPredicatesEqualsMethod = config.imposterStubPredicatesEqualsMethod;21const imposterStubPredicatesEqualsPathValue = config.imposterStubPredicatesEqualsPathValue;22const imposterStubPredicatesEqualsMethodValue = config.imposterStubPredicatesEqualsMethodValue;23const imposterStubPredicatesEqualsHeaders = config.imposterStubPredicatesEqualsHeaders;24const imposterStubPredicatesEqualsHeadersKey = config.imposterStubPredicatesEqualsHeadersKey;25const imposterStubPredicatesEqualsHeadersValue = config.imposterStubPredicatesEqualsHeadersValue;26const imposterStubPredicatesEqualsBody = config.imposterStubPredicatesEqualsBody;27const imposterStubPredicatesEqualsBodyValue = config.imposterStubPredicatesEqualsBodyValue;28const imposterStubPredicatesEqualsCaseSensitive = config.imposterStubPredicatesEqualsCaseSensitive;29const imposterStubPredicatesEqualsXPath = config.imposterStubPredicatesEqualsXPath;30const imposterStubPredicatesEqualsXPathValue = config.imposterStubPredicatesEqualsXPathValue;31const imposterStubPredicatesEqualsXPathNamespaces = config.imposterStubPredicatesEqualsXPathNamespaces;32const imposterStubPredicatesEqualsXPathNamespacesKey = config.imposterStubPredicatesEqualsXPathNamespacesKey;33const imposterStubPredicatesEqualsXPathNamespacesValue = config.imposterStubPredicatesEqualsXPathNamespacesValue;
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!!