Best JavaScript code snippet using mountebank
server.ts
Source:server.ts
...151app.use(morgan('dev'));152app.use(bodyParser.urlencoded({ extended: false }));153app.use(bodyParser.json());154app.use(cors());155// app.use(validateApiKey());156app.use((req: any, res: any, next: any) => {157 res.header('Access-Control-Allow-Origin', '*');158 res.header('Access-Control-Allow-Headers', 159 'Origin, X-Requested-With, Content-Type, Accept, Authorization'160 );161 if (req.method === 'OPTIONS') {162 res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');163 return res.status(200).json({});164 };165 next();166});167app.use((req: any, res: any, next: any) => {168 const error = new Error("Not found");169 next(error);...
auth-api-key.spec.js
Source:auth-api-key.spec.js
...15 var res = {16 status: function () { done(new Error('res.status() should not be called')); },17 json: function () { done(new Error('res.json() should not be called')); }18 };19 authApiKey.validateApiKey(req, res, function () { done(); });20 });21});22describe('auth-api-key.validateApiKey (with keys)', function () {23 before(function () {24 // Mock the keys25 authApiKey.setValidApiKeys(['123', ' 456 ']); // Spaces added around second code to test trim26 });27 it('should call next() with valid code (123) query parameter', function (done) {28 var req = { get: function () { return undefined; }, query: { code: '123' } };29 var res = {30 status: function () { done(new Error('res.status() should not be called')); },31 json: function () { done(new Error('res.json() should not be called')); },32 cookie: function () { }33 };34 authApiKey.validateApiKey(req, res, function () { done(); });35 });36 it('should call next() with valid code (456) query parameter', function (done) {37 var req = { get: function () { return undefined; }, query: { code: '456' } };38 var res = {39 status: function () { done(new Error('res.status() should not be called')); },40 json: function () { done(new Error('res.json() should not be called')); },41 cookie: function () { }42 };43 authApiKey.validateApiKey(req, res, function () { done(); });44 });45 it('should call next() with valid header (123) key', function (done) {46 var req = { get: function () { return "123"; }, query: {} };47 var res = {48 status: function () { done(new Error('res.status() should not be called')); },49 json: function () { done(new Error('res.json() should not be called')); },50 cookie: function () { }51 };52 authApiKey.validateApiKey(req, res, function () { done(); });53 });54 it('should call next() with valid header (456) key', function (done) {55 var req = { get: function () { return "456"; }, query: {} };56 var res = {57 status: function () { done(new Error('res.status() should not be called')); },58 json: function () { done(new Error('res.json() should not be called')); },59 cookie: function () { }60 };61 authApiKey.validateApiKey(req, res, function () { done(); });62 });63 it('should call next() with valid cookie (456) key', function (done) {64 var req = { get: function () { }, query: {}, cookies : { key : '456'} };65 var res = {66 status: function () { done(new Error('res.status() should not be called')); },67 json: function () { done(new Error('res.json() should not be called')); },68 cookie: function () { }69 };70 authApiKey.validateApiKey(req, res, function () { done(); });71 });72 it('should set correct cookie when cookie is sent', function (done) {73 var req = { get: function () { }, query: {}, cookies : { key : '456'} };74 var res = {75 status: function () { done(new Error('res.status() should not be called')); },76 json: function () { done(new Error('res.json() should not be called')); },77 cookie: function (x, y, z) { if (x == 'key' && y == '456' && z.httpOnly && z.secure) {done();} }78 };79 authApiKey.validateApiKey(req, res, function () {});80 });81 it('should set correct cookie when valid header is sent', function (done) {82 var req = { get: function () { return "456"; }, query: {} };83 var res = {84 status: function () { done(new Error('res.status() should not be called')); },85 json: function () { done(new Error('res.json() should not be called')); },86 cookie: function (x, y, z) { if (x == 'key' && y == '456' && z.httpOnly && z.secure) {done();} }87 };88 authApiKey.validateApiKey(req, res, function () {});89 });90 it('should return 401 without valid key', function (done) {91 var req = { get: function () { return undefined; }, query: {}, cookies : { key : 'dummy'} };92 var res = {93 status: function (s) { if (s == 401) return done(); },94 json: function () { }95 };96 authApiKey.validateApiKey(req, res, function () { new Error('next() should not be called'); });97 });98 it('should return 401 without valid key (key with spaces --> 456 <---)', function (done) {99 var req = { get: function () { return " 456 "; }, query: {}, cookies : { key : 'dummy'} };100 var res = {101 status: function (s) { if (s == 401) return done(); },102 json: function () { }103 };104 authApiKey.validateApiKey(req, res, function () { new Error('next() should not be called'); });105 });...
index.ts
Source:index.ts
1import { Router, Request, Response } from 'express';2import { UserController } from '@controllers/user';3import {4 validateApiKey,5 validateUserAccessToken,6 validateUserRefreshToken,7} from '@middleware/index';8import {9 validateSaveUserRequest,10 validateUserLoginRequest,11 validateUserUpdateRequest,12 validateOptVerificationRequest,13 validateResentOtpRequest,14 validateResetPasswordRequest,15 validateChangePasswordRequest,16 // validateAddressRequest,17 // validateAddressUpdateRequest,18 validateUserForgotPasswordRequest,19} from '@validations/user';20import { validate } from '@validations/index';21const userRouter = Router();22const userCtrl = new UserController();23userRouter.post(24 '/signup',25 validateApiKey,26 validateSaveUserRequest,27 validate,28 (req: Request, res: Response) => userCtrl.createUser(req, res),29);30userRouter.post(31 '/otp-verification',32 validateApiKey,33 validateOptVerificationRequest,34 validate,35 (req: Request, res: Response) => userCtrl.otpVerification(req, res),36);37userRouter.post(38 '/resent-otp',39 validateApiKey,40 validateResentOtpRequest,41 validate,42 (req: Request, res: Response) => userCtrl.resentOtp(req, res),43);44userRouter.post(45 '/login/:id',46 validateApiKey,47 validateUserLoginRequest,48 validate,49 (req: Request, res: Response) => userCtrl.userLogin(req, res),50);51userRouter.get('/me', validateApiKey, validateUserAccessToken, (req: Request, res: Response) =>52 userCtrl.getCurrentUserDetails(req, res),53);54userRouter.get('/token', validateApiKey, validateUserRefreshToken, (req: Request, res: Response) =>55 userCtrl.genrateNewToken(req, res),56);57userRouter.post(58 '/forgot-password',59 validateApiKey,60 validateUserForgotPasswordRequest,61 validate,62 (req: Request, res: Response) => userCtrl.forgotPassword(req, res),63);64userRouter.put(65 '/reset-password',66 validateApiKey,67 validateResetPasswordRequest,68 validate,69 (req: Request, res: Response) => userCtrl.resetPassword(req, res),70);71userRouter.put(72 '/change-password',73 validateApiKey,74 validateUserAccessToken,75 validateChangePasswordRequest,76 validate,77 (req: Request, res: Response) => userCtrl.changePassword(req, res),78);79userRouter.put(80 '/update',81 validateApiKey,82 validateUserAccessToken,83 validateUserUpdateRequest,84 validate,85 (req: Request, res: Response) => userCtrl.updateUserDetails(req, res),86);87userRouter.post(88 '/add-addresses',89 validateApiKey,90 validateUserAccessToken,91 (req: Request, res: Response) => userCtrl.addAddress(req, res),92);93// userRouter.put(94// '/update-address/:id',95// validateApiKey,96// validateUserAccessToken,97// validateAddressUpdateRequest,98// validate,99// (req: Request, res: Response) => userCtrl.updateAddress(req, res),100// );101userRouter.delete(102 '/delete-address/:id',103 validateApiKey,104 validateUserAccessToken,105 (req: Request, res: Response) => userCtrl.deleteAddress(req, res),106);107userRouter.get(108 '/get-user-addresses',109 validateApiKey,110 validateUserAccessToken,111 (req: Request, res: Response) => userCtrl.getAddresses(req, res),112);...
router.js
Source:router.js
1import express from 'express';2import rateLimit from 'express-rate-limit';3import { getWords, getWord } from '../controllers/words';4import { getExamples, getExample } from '../controllers/examples';5import { postDeveloper } from '../controllers/developers';6import { getStats } from '../controllers/stats';7import validId from '../middleware/validId';8import validateDeveloperBody from '../middleware/validateDeveloperBody';9import validateApiKey from '../middleware/validateApiKey';10import validateAdminApiKey from '../middleware/validateAdminApiKey';11import analytics from '../middleware/analytics';12const router = express.Router();13const FIFTEEN_MINUTES = 15 * 60 * 1000;14const REQUESTS_PER_MS = 20;15const createDeveloperLimiter = rateLimit({16 windowMs: FIFTEEN_MINUTES,17 max: REQUESTS_PER_MS,18});19// Google Analytics20router.use(analytics);21router.get('/words', validateApiKey, getWords);22router.get('/words/:id', validateApiKey, validId, getWord);23router.get('/examples', validateApiKey, getExamples);24router.get('/examples/:id', validateApiKey, validId, getExample);25router.post('/developers', createDeveloperLimiter, validateDeveloperBody, postDeveloper);26router.get('/stats', validateAdminApiKey, getStats);...
sampleTable.js
Source:sampleTable.js
1var azureMobileApps = require('azure-mobile-apps'),2 validateApiKey = require('../validateApiKey');3// Create a new table definition4var table = azureMobileApps.table();5// Access should be anonymous so that unauthenticated users are not rejected6// before our custom validateApiKey middleware runs.7table.access = 'anonymous';8// validate api key header prior to execution of any table operation9 table.use(validateApiKey, table.execute);10// to require api key authentication for only one operation (in this case insert)11// instead of table.use(validateApiKey, table.execute) use:12// table.insert.use(validateApiKey, table.operation);...
Using AI Code Generation
1const mb = require('mountebank');2const options = {3};4mb.create(options)5 .then(() => {6 {7 {8 {9 is: {10 }11 }12 }13 },14 {15 {16 {17 is: {18 }19 }20 }21 }22 ];23 return mb.post('/imposters', imposters);24 })25 .then(() => mb.get('/imposters'))26 .then(response => {27 console.log(JSON.stringify(response.body, null, 2));28 return mb.del('/imposters');29 })30 .then(() => mb.del('/imposters/4545'))31 .then(() => mb.del('/imposters/4546'))32 .then(() => mb.del('/imposters/4547'))33 .then(() => mb.put('/imposters/4545', {34 {35 {36 is: {37 }38 }39 }40 }))41 .catch(error => {42 console.error(JSON.stringify(error, null, 2));43 process.exit(1);44 });
Using AI Code Generation
1const mb = require('mountebank');2var options = {3};4mb.validateApiKey(options, '1234', function (error, response) {5 if (error) {6 console.log(error);7 }8 else {9 console.log(response);10 }11});12#### create(options, imposters, callback)13* `protocol` - The protocol for the imposter, either `http` or `tcp` (default `http`)14* `mutualAuth` - If true, the imposter will require mutual authentication (default `false`)15* `allowInjection` - If true, the imposter will allow JavaScript injection (default `false`)16#### get(options, callback)
Using AI Code Generation
1var mb = require('mountebank');2var client = mb.createClient({ port: 2525, allowInjection: true });3client.validateApiKey('1234').then(function (result) {4 console.log(result);5});6### createClient(options)7* `port` - port on which mountebank is listening (default: 2525)8* `protocol` - protocol to use (default: http)9* `host` - host on which mountebank is running (default: localhost)10* `allowInjection` - whether to allow JavaScript injection into imposters (default: false)11* `retry` - how many times to retry a failed request (default: 0)12* `timeout` - timeout in milliseconds for a request (default: 3000)13* `logger` - custom logger to use (default: console)14### createClient(options).get(url, [options])15* `retry` - how many times to retry a failed request (overrides global retry value)16* `timeout` - timeout in milliseconds for a request (overrides global timeout value)17* `logger` - custom logger to use (overrides global logger)18### createClient(options).post(url, data, [options])19* `retry` - how many times to retry a failed request (overrides global retry value)20* `timeout` - timeout in milliseconds for a request (overrides global timeout value)21* `logger` - custom logger to use (overrides global logger)22### createClient(options).put(url, data, [options])23* `retry` - how many times to retry a failed request (overrides global retry value)
Using AI Code Generation
1var mb = require('mountebank');2var mbHelper = {3 validateApiKey: function (request, response) {4 if (request.headers['x-api-key'] === 'test') {5 response.statusCode = 200;6 } else {7 response.statusCode = 401;8 }9 response.end();10 }11};12mb.create({13}, function (error, mbInstance) {14 if (error) {15 console.log('Error starting mountebank', error);16 } else {17 console.log('Mountebank started with pid', mbInstance.pid);18 mbInstance.addStub({19 predicates: [{20 equals: {21 headers: {22 }23 }24 }],25 responses: [{26 is: {27 headers: {28 },29 body: JSON.stringify({30 })31 }32 }]33 });34 mbInstance.addStub({35 predicates: [{36 equals: {37 headers: {38 }39 }40 }],41 responses: [{42 is: {43 headers: {44 },45 body: JSON.stringify({46 })47 }48 }]49 });50 mbInstance.addStub({51 predicates: [{52 equals: {53 headers: {54 'x-api-key': { 'matches': 'test.*' }55 }56 }57 }],58 responses: [{59 is: {60 headers: {61 },62 body: JSON.stringify({63 })64 }65 }]66 });67 mbInstance.addStub({68 predicates: [{69 equals: {
Using AI Code Generation
1var mb = require('./mountebank.js');2 console.log(isValid);3});4var mb = require('./mountebank.js');5 console.log(result);6});7var mb = require('./mountebank.js');8 console.log(result);9});10var mb = require('./mountebank.js');11 console.log(result);12});13var mb = require('./mountebank.js');14 console.log(result);15});16var mb = require('./mountebank.js');17 console.log(result);18});19var mb = require('./mountebank.js');20 console.log(result);21});22var mb = require('./mountebank.js');23var stub = {24 {25 is: {26 headers: {27 },28 body: JSON.stringify({29 })30 }31 }32};33 console.log(result);34});
Using AI Code Generation
1var mb = require('mountebank');2var mbHelper = require('mountebank-helper');3var mb = mbHelper.create({host: 'localhost', port: 2525});4mb.validateApiKey('1234')5 .then(function (result) {6 console.log(result);7 })8 .catch(function (error) {9 console.error(error);10 });11### create(options)12### getImposters()13### getImposter(port)14### getRequests(port)15### createImposter(imposter)16### deleteImposter(port)17### deleteAllImposters()18### deleteAllRequests()19### reset()20### getMountebankVersion()21### validateApiKey(apiKey)
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!!