Best JavaScript code snippet using mountebank
imposterTest.js
Source:imposterTest.js
...269 });270 it('responseFor should increment numberOfRequests and not record requests if recordRequests = false', async function () {271 server.resolver.resolve = mock().returns(Promise.resolve({}));272 const imposter = await Imposter.create(Protocol, { recordRequests: false }, logger, { recordRequests: false }, allow);273 await imposter.getResponseFor({});274 const json = await imposter.toJSON();275 assert.strictEqual(json.numberOfRequests, 1);276 assert.deepEqual(json.requests, []);277 });278 it('responseFor should increment numberOfRequests and record requests if imposter recordRequests = true', async function () {279 server.resolver.resolve = mock().returns(Promise.resolve({}));280 const imposter = await Imposter.create(Protocol, { recordRequests: true }, logger, { recordRequests: false }, allow);281 await imposter.getResponseFor({ request: 1 });282 const json = await imposter.toJSON();283 assert.strictEqual(json.numberOfRequests, 1);284 assert.strictEqual(json.requests.length, 1);285 });286 it('responseFor should increment numberOfRequests and record requests if global recordRequests = true', async function () {287 server.resolver.resolve = mock().returns(Promise.resolve({}));288 const imposter = await Imposter.create(Protocol, { recordRequests: false }, logger, { recordRequests: true }, allow);289 await imposter.getResponseFor({ request: 1 });290 const json = await imposter.toJSON();291 assert.strictEqual(json.numberOfRequests, 1);292 assert.strictEqual(json.requests.length, 1);293 });294 it('responseFor should add timestamp to recorded request', async function () {295 server.resolver.resolve = mock().returns(Promise.resolve({}));296 const imposter = await Imposter.create(Protocol, {}, logger, { recordRequests: true }, allow);297 await imposter.getResponseFor({ request: 1 });298 const json = await imposter.toJSON();299 assert.deepEqual(Object.keys(json.requests[0]).sort(), ['request', 'timestamp']);300 assert.strictEqual(json.requests[0].request, 1);301 });302 });303 describe('#getResponseFor', function () {304 it('responseFor should return error if ip check denied', async function () {305 const imposter = await Imposter.create(Protocol, {}, logger, {}, deny),306 response = await imposter.getResponseFor({});307 assert.deepEqual(response, { blocked: true, code: 'unauthorized ip address' });308 });309 it('should return default response if no match', async function () {310 const imposter = await Imposter.create(Protocol, {}, logger, {}, allow);311 await imposter.getResponseFor({});312 assert.ok(server.resolver.resolve.wasCalledWith({ is: {} }), server.resolver.resolve.message());313 });314 it('should always match if no predicate', async function () {315 const request = {316 stubs: [{ responses: [{ is: 'first stub' }] }]317 },318 imposter = await Imposter.create(Protocol, request, logger, {}, allow);319 await server.stubs.add(request.stubs[0]);320 await imposter.getResponseFor({ field: 'value' });321 assert.ok(server.resolver.resolve.wasCalledWith({ is: 'first stub' }), server.resolver.resolve.message());322 });323 it('should return first match', async function () {324 const request = {325 stubs: [326 { predicates: [{ equals: { field: '1' } }], responses: [{ is: 'first stub' }] },327 { predicates: [{ equals: { field: '2' } }], responses: [{ is: 'second stub' }] },328 { predicates: [{ equals: { field: '2' } }], responses: [{ is: 'third stub' }] }329 ]330 },331 imposter = await Imposter.create(Protocol, request, logger, {}, allow);332 await server.stubs.add(request.stubs[0]);333 await server.stubs.add(request.stubs[1]);334 await server.stubs.add(request.stubs[2]);335 await imposter.getResponseFor({ field: '2' });336 assert.ok(server.resolver.resolve.wasCalledWith({ is: 'second stub' }), server.resolver.resolve.message());337 });338 it('should return responses in order, looping around', async function () {339 const request = {340 stubs: [{ responses: [{ is: 'first response' }, { is: 'second response' }] }]341 },342 imposter = await Imposter.create(Protocol, request, logger, {}, allow);343 await server.stubs.add(request.stubs[0]);344 await imposter.getResponseFor({});345 assert.ok(server.resolver.resolve.wasCalledWith({ is: 'first response' }), server.resolver.resolve.message());346 await imposter.getResponseFor({});347 assert.ok(server.resolver.resolve.wasCalledWith({ is: 'second response' }), server.resolver.resolve.message());348 await imposter.getResponseFor({});349 assert.ok(server.resolver.resolve.wasCalledWith({ is: 'first response' }), server.resolver.resolve.message());350 });351 it('should repeat a response and continue looping', async function () {352 const firstResponse = { is: 'first response', repeat: 2 },353 secondResponse = { is: 'second response' },354 request = { stubs: [{ responses: [firstResponse, secondResponse] }] },355 imposter = await Imposter.create(Protocol, request, logger, {}, allow);356 await server.stubs.add(request.stubs[0]);357 await imposter.getResponseFor({});358 assert.ok(server.resolver.resolve.wasCalledWith(firstResponse), server.resolver.resolve.message());359 await imposter.getResponseFor({});360 assert.ok(server.resolver.resolve.wasCalledWith(firstResponse), server.resolver.resolve.message());361 await imposter.getResponseFor({});362 assert.ok(server.resolver.resolve.wasCalledWith(secondResponse), server.resolver.resolve.message());363 await imposter.getResponseFor({});364 assert.ok(server.resolver.resolve.wasCalledWith(firstResponse), server.resolver.resolve.message());365 await imposter.getResponseFor({});366 assert.ok(server.resolver.resolve.wasCalledWith(firstResponse), server.resolver.resolve.message());367 await imposter.getResponseFor({});368 assert.ok(server.resolver.resolve.wasCalledWith(secondResponse), server.resolver.resolve.message());369 });370 });371 describe('#resetRequests', function () {372 it('should delete requests and reset numberOfRequests', async function () {373 const imposter = await Imposter.create(Protocol, {}, logger, { recordRequests: true }, allow);374 await imposter.getResponseFor({});375 const requests = await server.stubs.loadRequests();376 assert.strictEqual(1, requests.length);377 const json = await imposter.toJSON();378 assert.strictEqual(1, json.numberOfRequests);379 await imposter.resetRequests();380 const secondRequests = await server.stubs.loadRequests();381 assert.strictEqual(0, secondRequests.length);382 const secondJSON = await imposter.toJSON();383 assert.strictEqual(0, secondJSON.numberOfRequests);384 });385 });...
alation-api.ts
Source:alation-api.ts
...31 return await response.json();32}33export async function getDataSources(): Promise<types.dataSource[]> {34 const url = `${await getBaseURL()}integration/v1/${constants.URI_MAP['datasource']}/`;35 return getResponseFor(url) as Promise<types.dataSource[]>;36}37export async function getSchemas(dataSourceId: number): Promise<types.schema[]> {38 const url = `${await getBaseURL()}integration/v2/${constants.URI_MAP.schema}/?ds_id=${dataSourceId}&limit=100&skip=0`;39 return getResponseFor(url) as Promise<types.schema[]>;40}41export async function getTables(schemaId: number): Promise<types.table[]> {42 const url = `${await getBaseURL()}integration/v2/${constants.URI_MAP.table}/?schema_id=${schemaId}&limit=100&skip=0`;43 return getResponseFor(url) as Promise<types.table[]>;44}45export async function getColumns(tableId: number): Promise<types.column[]> {46 const url = `${await getBaseURL()}integration/v2/${constants.URI_MAP.column}/?table_id=${tableId}&limit=100&skip=0`;47 return getResponseFor(url) as Promise<types.column[]>;48}49async function getResponseFor(url: string): Promise<types.baseEntity[]>;50async function getResponseFor(url: string, params: RequestInit): Promise<types.baseEntity[]>;51async function getResponseFor(url: string, returnJson: boolean): Promise<types.baseEntity[] | string>;52async function getResponseFor(53 url: string, params: RequestInit, returnJson: boolean): Promise<types.baseEntity[] | string>;54async function getResponseFor(55 url: string, paramsOrReturnJson?: RequestInit | boolean, returnJson?: boolean,56): Promise<types.baseEntity[] | string> {57 let params: RequestInit;58 if (typeof paramsOrReturnJson === 'boolean' || typeof paramsOrReturnJson === 'undefined') {59 returnJson = paramsOrReturnJson;60 params = {61 method: 'GET',62 headers: {63 'Accept': 'application/json',64 'TOKEN': await utils.getApiToken(),65 },66 };67 }68 params ??= paramsOrReturnJson as RequestInit;69 returnJson ??= true;70 const response = await grok.dapi.fetchProxy(url, params);71 return returnJson ? response.json() : response.text();72}73export async function getQueries(74 dataSourceId: number, saved: boolean = true, published: boolean = true): Promise<types.query[]> {75 const urlParams = `datasource_id=${dataSourceId}&saved=${saved}&published=${published}`;76 const url = `${await getBaseURL()}integration/v1/${constants.URI_MAP.query}/?${urlParams}`;77 const params = {78 method: 'GET',79 headers: {80 'Accept': 'application/json',81 'TOKEN': await utils.getApiToken(),82 },83 };84 const response = await grok.dapi.fetchProxy(url, params);85 return response.json();86}87export async function testQuery(execResultId: number): Promise<string> {88 const url =89 `${await getBaseURL()}integration/v1/${constants.URI_MAP.result}/${execResultId}/${constants.FORMAT.csv}/`;90 return getResponseFor(url, false) as Promise<string>;91}92export async function getDataSourceById(dataSourceId: number): Promise<types.dataSource> {93 const url = `${await getBaseURL()}integration/v1/${constants.URI_MAP.datasource}/${dataSourceId}`;94 const params = {95 method: 'GET',96 headers: {97 'Accept': 'application/json',98 'TOKEN': await utils.getApiToken(),99 },100 };101 const response = await grok.dapi.fetchProxy(url, params);102 return response.json();...
tile-configuration.controller.ts
Source:tile-configuration.controller.ts
...14@Controller('tile-configuration')15export class TileConfigurationController {16 constructor(private readonly tileConfigurationService: TileConfigurationService) {}17 @Get('')18 @ApiResponse({ type: getResponseFor(TileConfigurationEntity) })19 @AllowRoles([AuthRoles.SCHULER_ADMIN, AuthRoles.CUSTOMER_MAINTENANCE_MANAGER, AuthRoles.MAINTENANCE_PERSONELL])20 async getTileConfiguration(21 @Req() req: Request,22 ): Promise<DataResponse<TileConfigurationEntity[]>> {23 const tileConfiguration = await this.tileConfigurationService.getTileConfigurations(req.auth);24 return asResponse(tileConfiguration);25 }26 @Post('/')27 @ApiResponse({ type: getResponseFor(TileConfigurationEntity) })28 @AllowRoles([AuthRoles.SCHULER_ADMIN])29 async postTileConfiguration(30 @Req() req: Request,31 @Body(new JoiPipe(PostTileConfigurationDtoSchema))32 tileConfigurationsDto: PostTileConfigurationDto,33 ): Promise<DataResponse<TileConfigurationEntity>> {34 const tileConfiguration = await this.tileConfigurationService.createTileConfiguration(35 req.auth,36 {37 tileName: tileConfigurationsDto.tileName,38 desc: tileConfigurationsDto.desc,39 appUrl: tileConfigurationsDto.appUrl,40 iconUrl: tileConfigurationsDto.iconUrl,41 tileColor: tileConfigurationsDto.tileColor,42 tileTextColor: tileConfigurationsDto.tileTextColor,43 order: tileConfigurationsDto.order,44 },45 );46 return asResponse(tileConfiguration);47 }48 @Put('/change-position')49 @ApiResponse({ type: getResponseFor(TileConfigurationEntity) })50 @AllowRoles([AuthRoles.SCHULER_ADMIN])51 async changePositionGeneralSetting(52 @Req() req: Request,53 @Body()54 { fromId, toId }: ChangeTilePositionDto,55 ): Promise<DataResponse<TileConfigurationEntity>> {56 const tileConfigurations = await this.tileConfigurationService.changePosition(57 req.auth,58 fromId,59 toId,60 );61 return asResponse(tileConfigurations);62 }63 @Put('/:tileConfigurationId')64 @ApiResponse({ type: getResponseFor(TileConfigurationEntity) })65 @AllowRoles([AuthRoles.SCHULER_ADMIN])66 async putGeneralSetting(67 @Req() req: Request,68 @Param('tileConfigurationId')69 tileConfigurationId: number,70 @Body(new JoiPipe(PostTileConfigurationDtoSchema))71 tileConfigurationsDto: PostTileConfigurationDto,72 ): Promise<DataResponse<TileConfigurationEntity>> {73 const tileConfigurations = await this.tileConfigurationService.updateTileConfiguration(74 req.auth,75 tileConfigurationId,76 tileConfigurationsDto,77 );78 return asResponse(tileConfigurations);79 }80 @Delete('/:tileConfigurationId')81 @ApiResponse({ type: getResponseFor(TileConfigurationEntity) })82 @AllowRoles([AuthRoles.SCHULER_ADMIN])83 async deletePositionGeneralSetting(84 @Req() req: Request,85 @Param('tileConfigurationId')86 tileConfigurationId: number,87 ): Promise<DataResponse<boolean>> {88 const tileConfigurations = await this.tileConfigurationService.deleteTileConfiguration(89 req.auth,90 tileConfigurationId,91 );92 return asResponse(tileConfigurations);93 }...
Using AI Code Generation
1var http = require('http');2var options = {3 headers: {4 }5};6var req = http.request(options, function (res) {7 console.log('Status: ' + res.statusCode);8 console.log('Headers: ' + JSON.stringify(res.headers));9 res.setEncoding('utf8');10 res.on('data', function (body) {11 console.log('Body: ' + body);12 });13});14req.on('error', function (e) {15 console.log('problem with request: ' + e.message);16});17req.write(JSON.stringify({18 "stubs": [{19 "responses": [{20 "is": {21 }22 }]23 }]24}));25req.end();26var http = require('http');27var options = {28 headers: {29 }30};31var req = http.request(options, function (res) {32 console.log('Status: ' + res.statusCode);33 console.log('Headers: ' + JSON.stringify(res.headers));34 res.setEncoding('utf8');35 res.on('data', function (body) {36 console.log('Body: ' + body);37 });38});39req.on('error', function (e) {40 console.log('problem with request: ' + e.message);41});42req.write(JSON.stringify({43 "stubs": [{
Using AI Code Generation
1var request = require("request");2var options = {3 {4 'content-type': 'application/json' },5 { protocol: 'http',6 stubs: [ { responses: [ { is: { body: 'Hello, World!' } } ] } ] },7 json: true };8request(options, function (error, response, body) {9 if (error) throw new Error(error);10 console.log(body);11});12var request = require("request");13var options = {14 {15 'content-type': 'application/json' },16 { protocol: 'http',17 stubs: [ { responses: [ { is: { body: 'Hello, World!' } } ] } ] },18 json: true };19request(options, function (error, response, body) {20 if (error) throw new Error(error);21 console.log(body);22});23var request = require("request");24var options = {25 {26 'content-type': 'application/json' },27 { protocol: 'http',28 stubs: [ { responses: [ { is: { body: 'Hello, World!' } } ] } ] },29 json: true };30request(options, function (error, response, body) {31 if (error) throw new Error(error);32 console.log(body);33});34var request = require("request");35var options = {36 {
Using AI Code Generation
1var mb = require('mountebank');2var assert = require('assert');3var Q = require('q');4var response = {5 headers: { 'Content-Type': 'application/json' },6 body: { 'status': 'ok' }7};8var predicate = {9 equals: {10 }11};12var stub = {13 {14 }15};16var impostor = {17};18var options = {19 headers: {20 }21};22var deferred = Q.defer();23var req = mb.createRequest(options, function (res) {24 res.on('end', function () {25 deferred.resolve();26 });27});28req.write(JSON.stringify(impostor));29req.end();30deferred.promise.then(function () {31 var options = {32 headers: {33 }34 };35 var deferred = Q.defer();36 var req = mb.createRequest(options, function (res) {37 res.on('end', function () {38 deferred.resolve();39 });40 });41 req.write(JSON.stringify({}));42 req.end();43 return deferred.promise;44}).then(function () {45 var options = {46 headers: {47 }48 };49 var deferred = Q.defer();50 var req = mb.createRequest(options, function (res) {51 res.on('end', function () {52 deferred.resolve();53 });54 });55 req.write(JSON.stringify({}));56 req.end();57 return deferred.promise;58}).then(function () {59 var options = {
Using AI Code Generation
1var mb = require('mountebank');2var options = {3};4 {5 {6 {7 equals: {8 }9 }10 {11 is: {12 headers: {13 },14 body: {15 }16 }17 }18 }19 }20];21mb.create(options, imposters).then(function () {22 mb.getResponseFor({23 }).then(function (response) {24 console.log('response', response);25 }).catch(function (error) {26 console.log('error', error);27 });28}).catch(function (error) {29 console.log('error', error);30});31var assert = require('assert');32var mb = require('mountebank');33var options = {34};35 {36 {37 {38 equals: {39 }40 }41 {42 is: {43 headers: {44 },45 body: {46 }47 }48 }49 }50 }51];52describe('Test', function () {53 before(function () {54 return mb.create(options, imposters);55 });56 it('should return response', function () {57 return mb.getResponseFor({58 }).then(function (response) {59 assert.deepEqual(response.body, { name: 'test' });60 });61 });62});63var assert = require('assert');
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var imposter = {4 {5 {6 is: {7 }8 }9 }10};11mb.create(server, imposter).then(function (response) {12 console.log('Imposter created');13 return mb.get(server, imposter.port, '/').then(function (response) {14 console.log('Response received');15 console.log(response.body);16 });17});18var mb = require('mountebank');19var port = 2525;20var imposter = {21 {22 {23 is: {24 }25 }26 }27};28mb.create(server, imposter).then(function (response) {29 console.log('Imposter created');30 return mb.get(server, imposter.port, '/').then(function (response) {31 console.log('Response received');32 console.log(response.body);33 });34});35var mb = require('mountebank');36var port = 2525;37var imposter = {38 {39 {40 is: {41 }42 }43 }44};45mb.create(server, imposter).then(function (response) {46 console.log('Imposter created');47 return mb.get(server, imposter.port, '/').then(function (response) {48 console.log('Response received');49 console.log(response.body);50 });51});52var mb = require('mountebank');53var port = 2525;54var imposter = {
Using AI Code Generation
1var imposter = require('mountebank').create();2var port = 2525;3var stub = {4 {5 is: {6 headers: {7 },8 body: {9 }10 }11 }12};13imposter.addStub(stub);14imposter.start(port);15var imposter = require('mountebank').create();16var port = 2525;17var stub = {18 {19 is: {20 headers: {21 },22 body: {23 }24 }25 }26};27imposter.addStub(stub);28imposter.start(port);29var imposter = require('mountebank').create();30var port = 2525;31var stub = {32 {33 is: {34 headers: {35 },36 body: {37 }38 }39 }40};41imposter.addStub(stub);42imposter.start(port);43var imposter = require('mountebank').create();44var port = 2525;45var stub = {46 {47 is: {48 headers: {49 },50 body: {51 }52 }53 }54};55imposter.addStub(stub);56imposter.start(port);57var imposter = require('mountebank').create();58var port = 2525;59var stub = {60 {61 is: {62 headers: {63 },64 body: {65 }66 }67 }68};69imposter.addStub(stub);70imposter.start(port);
Using AI Code Generation
1var imposter = require('mountebank').create();2var port = 2525;3var protocol = 'http';4 {5 {6 equals: {7 }8 }9 {10 is: {11 }12 }13 }14];15imposter.addStub(stubs);16imposter.start(port, protocol, function (error) {17 if (error) {18 console.log('Error starting imposter: ' + error.message);19 } else {20 console.log('Imposter started');21 }22});23var imposter = require('mountebank').create();24var port = 2525;25var protocol = 'http';26 {27 {28 equals: {29 }30 }31 {32 is: {33 }34 }35 }36];37imposter.addStub(stubs);38imposter.start(port, protocol, function (error) {39 if (error) {40 console.log('Error starting imposter: ' + error.message);41 } else {42 console.log('Imposter started');43 }44});45var request = {46 headers: {47 },48 query: {49 }50};51imposter.getResponseFor(request, function (error, response) {52 if (error) {53 console.log('Error getting response: ' + error.message);54 } else {55 console.log('Response received');56 }57});58var request = {59 headers: {60 },61 query: {62 }63};64imposter.getResponseFor(request, function (error, response) {65 if (error) {66 console.log('Error getting response: ' +
Using AI Code Generation
1var mountebank = require('mountebank');2var response = mb.getResponseFor({3});4console.log(response.statusCode);5var mountebank = require('mountebank');6var response = mb.postResponseFor({7}, {8 headers: {9 },10});11console.log(response.statusCode);12var mountebank = require('mountebank');13var response = mb.deleteResponseFor({14});15console.log(response.statusCode);16var mountebank = require('mountebank');17var response = mb.putResponseFor({18}, {19 headers: {20 },21});22console.log(response.statusCode);23var mountebank = require('mountebank');24var response = mb.getResponseFor({
Using AI Code Generation
1var request = require('request');2var mbHelper = require('./mbHelper');3var getResponseFor = mbHelper.getResponseFor;4var port = 2525;5var stub = {6{7{8"is": {9"headers": {10},11}12}13}14};15request.post({16}, function (error, response, body) {17console.log(body);18getResponseFor(url, port, function (error, response, body) {19console.log(body);20});21});22var request = require('request');23exports.getResponseFor = function (url, port, callback) {24request.get({25}, function (error, response, body) {26var imposter = body[0];27var request = imposter.requests[0];28request.method = request.method.toLowerCase();29request.json = true;30request.headers = request.headers || {};31request.headers.host = 'localhost:' + port;32request.body = request.body || '';33request.qs = request.query || '';34request.callback = callback;35request.resolveWithFullResponse = true;36request.simple = false;37request.jar = true;38request.followAllRedirects = true;39request.maxRedirects = 10;40request.forever = true;41request.time = true;42request.gzip = true;43request.timeout = 10000;44request.pool = {45};46request.strictSSL = false;47request.agentOptions = {48};49request.agentClass = require('https').Agent;50request.agentOptions = {51};52request.forever = true;53request.rejectUnauthorized = false;54request.secureProtocol = 'TLSv1_method';
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!!