Best JavaScript code snippet using mountebank
imposterControllerTest.js
Source:imposterControllerTest.js
1'use strict';2const assert = require('assert'),3 mock = require('../mock').mock,4 Controller = require('../../src/controllers/imposterController'),5 ImpostersRepo = require('../../src/models/inMemoryImpostersRepository'),6 FakeResponse = require('../fakes/fakeResponse'),7 Request = require('../fakes/fakeRequest');8function imposterize (config) {9 const cloned = JSON.parse(JSON.stringify(config)),10 result = { creationRequest: cloned };11 Object.keys(config).forEach(key => {12 if (typeof config[key] === 'function') {13 result[key] = config[key];14 }15 });16 result.port = config.port;17 return result;18}19describe('ImposterController', function () {20 describe('#get', function () {21 it('should return JSON for imposter at given id', async function () {22 const response = FakeResponse.create(),23 first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },24 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },25 repo = ImpostersRepo.create(),26 controller = Controller.create({}, repo);27 await repo.add(imposterize(first));28 await repo.add(imposterize(second));29 await controller.get(Request.to('/imposters/2', { id: 2 }), response);30 assert.strictEqual(response.body, 'secondJSON');31 });32 it('should return replayable JSON for imposter at given id if replayable querystring set', async function () {33 const response = FakeResponse.create(),34 firstImposter = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },35 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },36 repo = ImpostersRepo.create(),37 controller = Controller.create({}, repo);38 await repo.add(imposterize(firstImposter));39 await repo.add(imposterize(second));40 await controller.get(Request.to('/imposters/2?replayable=true', { id: 2 }), response);41 assert.strictEqual(response.body, 'secondJSON');42 assert.ok(second.toJSON.wasCalledWith({ replayable: true, removeProxies: false }), second.toJSON.message());43 });44 it('should return removeProxies JSON for imposter at given id if removeProxies querystring set', async function () {45 const response = FakeResponse.create(),46 first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },47 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },48 repo = ImpostersRepo.create(),49 controller = Controller.create({}, repo);50 await repo.add(imposterize(first));51 await repo.add(imposterize(second));52 await controller.get(Request.to('/imposters/2?removeProxies=true', { id: 2 }), response);53 assert.strictEqual(response.body, 'secondJSON');54 assert.ok(second.toJSON.wasCalledWith({ replayable: false, removeProxies: true }), second.toJSON.message());55 });56 it('should return replayable and removeProxies JSON for imposter at given id if both querystring values set', async function () {57 const response = FakeResponse.create(),58 first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },59 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },60 repo = ImpostersRepo.create(),61 controller = Controller.create({}, repo);62 await repo.add(imposterize(first));63 await repo.add(imposterize(second));64 await controller.get(Request.to('/imposters/2?removeProxies=true&replayable=true', { id: 2 }), response);65 assert.strictEqual(response.body, 'secondJSON');66 assert.ok(second.toJSON.wasCalledWith({ replayable: true, removeProxies: true }), second.toJSON.message());67 });68 it('should return normal JSON for imposter at given id if both replayable and removeProxies querystrings are false', async function () {69 const response = FakeResponse.create(),70 first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },71 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },72 repo = ImpostersRepo.create(),73 controller = Controller.create({}, repo);74 await repo.add(imposterize(first));75 await repo.add(imposterize(second));76 await controller.get(Request.to('/imposters/2?replayable=false&removeProxies=false', { id: 2 }), response);77 assert.strictEqual(response.body, 'secondJSON');78 assert.ok(second.toJSON.wasCalledWith({ replayable: false, removeProxies: false }), second.toJSON.message());79 });80 });81 describe('#del', function () {82 it('should stop the imposter', async function () {83 const response = FakeResponse.create(),84 imposter = {85 port: 1,86 stop: mock().returns(Promise.resolve(true)),87 toJSON: mock().returns(Promise.resolve('JSON'))88 },89 repo = ImpostersRepo.create(),90 controller = Controller.create({}, repo);91 await repo.add(imposterize(imposter));92 await controller.del(Request.to('/imposters/1', { id: 1 }), response);93 assert.ok(imposter.stop.wasCalled());94 });95 it('should remove the imposter from the list', async function () {96 const response = FakeResponse.create(),97 imposter = {98 port: 1,99 stop: mock().returns(Promise.resolve(true)),100 toJSON: mock().returns(Promise.resolve('JSON'))101 },102 repo = ImpostersRepo.create(),103 controller = Controller.create({}, repo);104 await repo.add(imposterize(imposter));105 await controller.del(Request.to('/imposters/1', { id: 1 }), response);106 const all = await repo.all();107 assert.deepEqual(all, []);108 });109 it('should send request even if no imposter exists', async function () {110 const response = FakeResponse.create(),111 repo = ImpostersRepo.create(),112 controller = Controller.create({}, repo);113 await controller.del(Request.to('/imposters/1', { id: 1 }), response);114 assert.deepEqual(response.body, {});115 });116 it('should return replayable JSON for imposter at given id if replayable querystring set', async function () {117 const response = FakeResponse.create(),118 imposter = {119 port: 1,120 stop: mock().returns(Promise.resolve(true)),121 toJSON: mock().returns(Promise.resolve('JSON'))122 },123 repo = ImpostersRepo.create(),124 controller = Controller.create({}, repo);125 await repo.add(imposterize(imposter));126 await controller.del(Request.to('/imposters/1?replayable=true', { id: 1 }), response);127 assert.ok(imposter.toJSON.wasCalledWith({ replayable: true, removeProxies: false }), imposter.toJSON.message());128 });129 it('should return removeProxies JSON for imposter at given id if removeProxies querystring set', async function () {130 const response = FakeResponse.create(),131 imposter = {132 port: 1,133 stop: mock().returns(Promise.resolve(true)),134 toJSON: mock().returns(Promise.resolve('JSON'))135 },136 repo = ImpostersRepo.create(),137 controller = Controller.create({}, repo);138 await repo.add(imposterize(imposter));139 await controller.del(Request.to('/imposters/1?removeProxies=true', { id: 1 }), response);140 assert.ok(imposter.toJSON.wasCalledWith({ replayable: false, removeProxies: true }), imposter.toJSON.message());141 });142 it('should return replayable and removeProxies JSON for imposter at given id if both querystring values set', async function () {143 const response = FakeResponse.create(),144 imposter = {145 port: 1,146 stop: mock().returns(Promise.resolve(true)),147 toJSON: mock().returns(Promise.resolve('JSON'))148 },149 repo = ImpostersRepo.create(),150 controller = Controller.create({}, repo);151 await repo.add(imposterize(imposter));152 await controller.del(Request.to('/imposters/1?removeProxies=true&replayable=true', { id: 1 }), response);153 assert.ok(imposter.toJSON.wasCalledWith({ replayable: true, removeProxies: true }), imposter.toJSON.message());154 });155 it('should send default JSON for the deleted the imposter if both replayable and removeProxies querystrings are missing', async function () {156 const response = FakeResponse.create(),157 imposter = {158 port: 1,159 stop: mock().returns(Promise.resolve(true)),160 toJSON: mock().returns(Promise.resolve('JSON'))161 },162 repo = ImpostersRepo.create(),163 controller = Controller.create({}, repo);164 await repo.add(imposterize(imposter));165 await controller.del(Request.to('/imposters/1', { id: 1 }), response);166 assert.ok(imposter.toJSON.wasCalledWith({ replayable: false, removeProxies: false }), imposter.toJSON.message());167 });168 });169 describe('#putStubs', function () {170 it('should return a 400 if no stubs element', async function () {171 const response = FakeResponse.create(),172 imposter = {173 port: 1,174 toJSON: mock().returns(Promise.resolve({})),175 overwriteStubs: mock()176 },177 logger = require('../fakes/fakeLogger').create(),178 repo = ImpostersRepo.create(),179 controller = Controller.create({}, repo, logger, false);180 await repo.add(imposterize(imposter));181 await controller.putStubs({ params: { id: 1 }, body: {} }, response);182 assert.strictEqual(response.statusCode, 400);183 assert.strictEqual(response.body.errors.length, 1);184 assert.strictEqual(response.body.errors[0].code, 'bad data');185 });186 it('should return a 400 if no stubs is not an array', async function () {187 const response = FakeResponse.create(),188 imposter = {189 port: 1,190 toJSON: mock().returns(Promise.resolve({})),191 overwriteStubs: mock()192 },193 repo = ImpostersRepo.create(),194 logger = require('../fakes/fakeLogger').create(),195 controller = Controller.create({}, repo, logger, false),196 request = {197 params: { id: 1 },198 body: { stubs: 1 }199 };200 await repo.add(imposterize(imposter));201 await controller.putStubs(request, response);202 assert.strictEqual(response.statusCode, 400);203 assert.strictEqual(response.body.errors.length, 1);204 assert.strictEqual(response.body.errors[0].code, 'bad data');205 });206 it('should return a 400 if no stub fails dry run validation', async function () {207 const response = FakeResponse.create(),208 imposter = {209 port: 1,210 protocol: 'test',211 creationRequest: { port: 1, protocol: 'test', stubs: [{}] },212 toJSON: mock().returns(Promise.resolve({ port: 1, protocol: 'test', stubs: [{}] }))213 },214 repo = ImpostersRepo.create(),215 Protocol = { testRequest: {} },216 logger = require('../fakes/fakeLogger').create(),217 controller = Controller.create({ test: Protocol }, repo, logger, false),218 request = {219 params: { id: 1 },220 body: { stubs: [{ responses: [{ invalid: 1 }] }] }221 };222 await repo.add(imposterize(imposter));223 await controller.putStubs(request, response);224 assert.strictEqual(response.statusCode, 400);225 assert.strictEqual(response.body.errors.length, 1);226 assert.strictEqual(response.body.errors[0].code, 'bad data');227 });228 it('should return a 400 if trying to add injection without --allowInjection set', async function () {229 const response = FakeResponse.create(),230 imposter = {231 port: 1,232 protocol: 'test',233 toJSON: mock().returns(Promise.resolve({ protocol: 'test' }))234 },235 repo = ImpostersRepo.create(),236 Protocol = { testRequest: {} },237 logger = require('../fakes/fakeLogger').create(),238 controller = Controller.create({ test: Protocol }, repo, logger, false),239 request = {240 params: { id: 1 },241 body: { stubs: [{ responses: [{ inject: '() => {}' }] }] }242 };243 await repo.add(imposterize(imposter));244 await controller.putStubs(request, response);245 assert.strictEqual(response.statusCode, 400);246 assert.strictEqual(response.body.errors.length, 1);247 assert.strictEqual(response.body.errors[0].code, 'invalid injection');248 });249 });250 describe('#putStub', function () {251 it('should return a 404 if stubIndex is not an integer', async function () {252 const response = FakeResponse.create(),253 imposter = {254 port: 1,255 protocol: 'test',256 stubsJSON: mock().returns(Promise.resolve([]))257 },258 repo = ImpostersRepo.create(),259 Protocol = { testRequest: {} },260 logger = require('../fakes/fakeLogger').create(),261 controller = Controller.create({ test: Protocol }, repo, logger, false),262 request = {263 params: { id: 1, stubIndex: 'test' },264 body: { stubs: [{ responses: [{ is: 'response' }] }] }265 };266 await repo.add(imposterize(imposter));267 await controller.putStub(request, response);268 assert.strictEqual(response.statusCode, 404);269 assert.strictEqual(response.body.errors.length, 1);270 assert.deepEqual(response.body.errors[0], {271 code: 'bad data',272 message: "'stubIndex' must be a valid integer, representing the array index position of the stub to replace"273 });274 });275 it('should return a 404 if stubIndex is less than 0', async function () {276 const response = FakeResponse.create(),277 imposter = {278 port: 1,279 protocol: 'test',280 stubsJSON: mock().returns(Promise.resolve([]))281 },282 repo = ImpostersRepo.create(),283 Protocol = { testRequest: {} },284 logger = require('../fakes/fakeLogger').create(),285 controller = Controller.create({ test: Protocol }, repo, logger, false),286 request = {287 params: { id: 1, stubIndex: -1 },288 body: { stubs: [{ responses: [{ is: 'response' }] }] }289 };290 await repo.add(imposterize(imposter));291 await controller.putStub(request, response);292 assert.strictEqual(response.statusCode, 404);293 assert.strictEqual(response.body.errors.length, 1);294 assert.deepEqual(response.body.errors[0], {295 code: 'bad data',296 message: "'stubIndex' must be a valid integer, representing the array index position of the stub to replace"297 });298 });299 it('should return a 404 if stubIndex is greater then highest index of stubs array', async function () {300 const response = FakeResponse.create(),301 imposter = {302 port: 1,303 protocol: 'test',304 stubsJSON: mock().returns(Promise.resolve([0, 1, 2]))305 },306 repo = ImpostersRepo.create(),307 Protocol = { testRequest: {} },308 logger = require('../fakes/fakeLogger').create(),309 controller = Controller.create({ test: Protocol }, repo, logger, false),310 request = {311 params: { id: 1, stubIndex: 3 },312 body: { stubs: [{ responses: [{ is: 'response' }] }] }313 };314 await repo.add(imposterize(imposter));315 await controller.putStub(request, response);316 assert.strictEqual(response.statusCode, 404);317 assert.strictEqual(response.body.errors.length, 1);318 assert.deepEqual(response.body.errors[0], {319 code: 'bad data',320 message: "'stubIndex' must be a valid integer, representing the array index position of the stub to replace"321 });322 });323 it('should return a 400 if no stub fails dry run validation', async function () {324 const response = FakeResponse.create(),325 imposter = {326 port: 1,327 protocol: 'test',328 toJSON: mock().returns(Promise.resolve({ protocol: 'test' })),329 creationRequest: { port: 1, protocol: 'test', stubs: [{}] }330 },331 repo = ImpostersRepo.create(),332 Protocol = { testRequest: {} },333 logger = require('../fakes/fakeLogger').create(),334 controller = Controller.create({ test: Protocol }, repo, logger, false),335 request = {336 params: { id: 1, stubIndex: 0 },337 body: { responses: [{ INVALID: 'response' }] }338 };339 await repo.add(imposter);340 await controller.putStub(request, response);341 assert.strictEqual(response.statusCode, 400);342 assert.strictEqual(response.body.errors.length, 1);343 assert.deepEqual(response.body.errors[0], {344 code: 'bad data',345 message: 'unrecognized response type',346 source: { INVALID: 'response' }347 });348 });349 it('should return a 400 if no adding inject without --allowInjection', async function () {350 const response = FakeResponse.create(),351 imposter = {352 port: 1,353 protocol: 'test',354 toJSON: mock().returns(Promise.resolve({ protocol: 'test' })),355 creationRequest: { port: 1, protocol: 'test', stubs: [{}] }356 },357 repo = ImpostersRepo.create(),358 Protocol = { testRequest: {} },359 logger = require('../fakes/fakeLogger').create(),360 controller = Controller.create({ test: Protocol }, repo, logger, false),361 request = {362 params: { id: 1, stubIndex: 0 },363 body: { responses: [{ inject: '() => {}' }] }364 };365 await repo.add(imposter);366 await controller.putStub(request, response);367 assert.strictEqual(response.statusCode, 400);368 assert.strictEqual(response.body.errors.length, 1);369 assert.deepEqual(response.body.errors[0], {370 code: 'invalid injection',371 message: 'JavaScript injection is not allowed unless mb is run with the --allowInjection flag',372 source: { responses: [{ inject: '() => {}' }] }373 });374 });375 });376 describe('#deleteStub', function () {377 it('should return a 404 if stubIndex is greater then highest index of stubs array', async function () {378 const response = FakeResponse.create(),379 imposter = {380 port: 1,381 protocol: 'test',382 stubsJSON: mock().returns(Promise.resolve([0, 1, 2]))383 },384 repo = ImpostersRepo.create(),385 Protocol = { testRequest: {} },386 logger = require('../fakes/fakeLogger').create(),387 controller = Controller.create({ test: Protocol }, repo, logger, false),388 request = {389 params: { id: 1, stubIndex: 3 },390 body: { stubs: [{ responses: [{ is: 'response' }] }] }391 };392 await repo.add(imposterize(imposter));393 await controller.deleteStub(request, response);394 assert.strictEqual(response.statusCode, 404);395 assert.strictEqual(response.body.errors.length, 1);396 assert.deepEqual(response.body.errors[0], {397 code: 'bad data',398 message: "'stubIndex' must be a valid integer, representing the array index position of the stub to replace"399 });400 });401 });...
impostersControllerTest.js
Source:impostersControllerTest.js
1'use strict';2const assert = require('assert'),3 mock = require('../mock').mock,4 Controller = require('../../src/controllers/impostersController'),5 FakeResponse = require('../fakes/fakeResponse'),6 FakeLogger = require('../fakes/fakeLogger'),7 ImpostersRepo = require('../../src/models/inMemoryImpostersRepository'),8 Request = require('../fakes/fakeRequest');9function imposterize (config) {10 const cloned = JSON.parse(JSON.stringify(config)),11 result = { creationRequest: cloned };12 Object.keys(config).forEach(key => {13 if (typeof config[key] === 'function') {14 result[key] = config[key];15 }16 });17 result.port = config.port;18 return result;19}20describe('ImpostersController', function () {21 let response;22 beforeEach(function () {23 response = FakeResponse.create();24 });25 describe('#get', function () {26 it('should send an empty array if no imposters', async function () {27 const impostersRepo = ImpostersRepo.create(),28 controller = Controller.create({}, impostersRepo, null, false);29 await controller.get(Request.to('/imposters'), response);30 assert.deepEqual(response.body, { imposters: [] });31 });32 it('should send list JSON for all imposters by default', async function () {33 const first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },34 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },35 repo = ImpostersRepo.create(),36 controller = Controller.create({}, repo, null, false);37 await repo.add(imposterize(first));38 await repo.add(imposterize(second));39 await controller.get(Request.to('/imposters'), response);40 assert.deepEqual(response.body, { imposters: ['firstJSON', 'secondJSON'] });41 assert.ok(first.toJSON.wasCalledWith({ replayable: false, removeProxies: false, list: true }), first.toJSON.message());42 assert.ok(second.toJSON.wasCalledWith({ replayable: false, removeProxies: false, list: true }), second.toJSON.message());43 });44 it('should send replayable JSON for all imposters if querystring present', async function () {45 const first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },46 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },47 repo = ImpostersRepo.create(),48 controller = Controller.create({}, repo, null, false);49 await repo.add(imposterize(first));50 await repo.add(imposterize(second));51 await controller.get(Request.to('/imposters?replayable=true'), response);52 assert.deepEqual(response.body, { imposters: ['firstJSON', 'secondJSON'] });53 assert.ok(first.toJSON.wasCalledWith({ replayable: true, removeProxies: false, list: false }), first.toJSON.message());54 assert.ok(second.toJSON.wasCalledWith({ replayable: true, removeProxies: false, list: false }), second.toJSON.message());55 });56 it('should send replayable and removeProxies JSON for all imposters if querystring present', async function () {57 const first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },58 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },59 repo = ImpostersRepo.create(),60 controller = Controller.create({}, repo, null, false);61 await repo.add(imposterize(first));62 await repo.add(imposterize(second));63 await controller.get(Request.to('/imposters?replayable=true&removeProxies=true'), response);64 assert.deepEqual(response.body, { imposters: ['firstJSON', 'secondJSON'] });65 assert.ok(first.toJSON.wasCalledWith({ replayable: true, removeProxies: true, list: false }), first.toJSON.message());66 assert.ok(second.toJSON.wasCalledWith({ replayable: true, removeProxies: true, list: false }), second.toJSON.message());67 });68 });69 describe('#post', function () {70 let request, imposter, imposters, Protocol, controller, logger;71 beforeEach(function () {72 request = { body: {}, socket: { remoteAddress: 'host', remotePort: 'port' } };73 imposter = {74 url: 'imposter-url',75 toJSON: mock().returns(Promise.resolve('JSON'))76 };77 imposters = ImpostersRepo.create();78 Protocol = {79 name: 'http',80 Validator: {81 create: mock().returns({ validate: mock().returns(Promise.resolve({ isValid: true })) })82 },83 createImposterFrom: creationRequest => {84 imposter.creationRequest = creationRequest;85 return Promise.resolve(imposter);86 }87 };88 logger = FakeLogger.create();89 controller = Controller.create({ http: Protocol }, imposters, logger, false);90 });91 it('should return a 201 with the Location header set', async function () {92 request.body = { port: 3535, protocol: 'http' };93 imposter.url = 'http://localhost/servers/3535';94 await controller.post(request, response);95 assert.strictEqual(response.headers.Location, 'http://localhost/servers/3535');96 assert.strictEqual(response.statusCode, 201);97 });98 it('should return imposter JSON', async function () {99 request.body = { port: 3535, protocol: 'http' };100 await controller.post(request, response);101 assert.strictEqual(response.body, 'JSON');102 });103 it('should add new imposter to list of all imposters', async function () {104 imposter.port = 3535;105 request.body = { protocol: 'http' };106 await controller.post(request, response);107 const allImposters = await imposters.all();108 assert.deepEqual(allImposters, [imposter]);109 });110 it('should return a 400 for a floating point port', async function () {111 request.body = { protocol: 'http', port: '123.45' };112 await controller.post(request, response);113 assert.strictEqual(response.statusCode, 400);114 assert.deepEqual(response.body, {115 errors: [{116 code: 'bad data',117 message: "invalid value for 'port'"118 }]119 });120 });121 it('should return a 400 for a missing protocol', async function () {122 request.body = { port: 3535 };123 await controller.post(request, response);124 assert.strictEqual(response.statusCode, 400);125 assert.deepEqual(response.body, {126 errors: [{127 code: 'bad data',128 message: "'protocol' is a required field"129 }]130 });131 });132 it('should return a 400 for unsupported protocols', async function () {133 request.body = { port: 3535, protocol: 'unsupported' };134 await controller.post(request, response);135 assert.strictEqual(response.statusCode, 400);136 assert.strictEqual(response.body.errors.length, 1);137 assert.strictEqual(response.body.errors[0].code, 'bad data');138 });139 it('should aggregate multiple errors', async function () {140 request.body = { port: -1, protocol: 'invalid' };141 await controller.post(request, response);142 assert.strictEqual(response.body.errors.length, 2, response.body.errors);143 });144 it('should return a 403 for insufficient access', async function () {145 Protocol.createImposterFrom = mock().returns(Promise.reject({146 code: 'insufficient access',147 key: 'value'148 }));149 request.body = { port: 3535, protocol: 'http' };150 await controller.post(request, response);151 assert.strictEqual(response.statusCode, 403);152 assert.deepEqual(response.body, {153 errors: [{154 code: 'insufficient access',155 key: 'value'156 }]157 });158 });159 it('should return a 400 for other protocol creation errors', async function () {160 Protocol.createImposterFrom = mock().returns(Promise.reject('ERROR'));161 request.body = { port: 3535, protocol: 'http' };162 await controller.post(request, response);163 assert.strictEqual(response.statusCode, 400);164 assert.deepEqual(response.body, { errors: ['ERROR'] });165 });166 it('should not call protocol validation if there are common validation failures', async function () {167 Protocol.Validator = { create: mock() };168 request.body = { protocol: 'invalid' };169 await controller.post(request, response);170 assert.ok(!Protocol.Validator.create.wasCalled());171 });172 it('should validate with Protocol if there are no common validation failures', async function () {173 Protocol.validate = mock().returns(Promise.resolve(['ERRORS']));174 request.body = { port: 3535, protocol: 'http' };175 await controller.post(request, response);176 assert.strictEqual(response.statusCode, 400);177 assert.deepEqual(response.body, { errors: ['ERRORS'] });178 });179 });180 describe('#del', function () {181 const stopMock = () => mock().returns(Promise.resolve(true));182 it('should delete all imposters', async function () {183 const first = { port: 1, stop: stopMock(), toJSON: mock().returns(Promise.resolve('firstJSON')) },184 second = { port: 2, stop: stopMock(), toJSON: mock().returns(Promise.resolve('secondJSON')) },185 repo = ImpostersRepo.create(),186 controller = Controller.create({}, repo, {}, false);187 await repo.add(imposterize(first));188 await repo.add(imposterize(second));189 await controller.del(Request.to('/imposters'), response);190 const allImposters = await repo.all();191 assert.deepEqual(allImposters, []);192 });193 it('should call stop on all imposters', async function () {194 const first = { port: 1, stop: mock(), toJSON: mock().returns(Promise.resolve('firstJSON')) },195 second = { port: 2, stop: mock(), toJSON: mock().returns(Promise.resolve('secondJSON')) },196 repo = ImpostersRepo.create(),197 controller = Controller.create({}, repo, {}, false);198 await repo.add(imposterize(first));199 await repo.add(imposterize(second));200 await controller.del(Request.to('/imposters'), response);201 assert.ok(first.stop.wasCalled());202 assert.ok(second.stop.wasCalled());203 });204 it('should send replayable JSON for all imposters by default', async function () {205 const first = { port: 1, stop: stopMock(), toJSON: mock().returns(Promise.resolve('firstJSON')) },206 second = { port: 2, stop: stopMock(), toJSON: mock().returns(Promise.resolve('secondJSON')) },207 repo = ImpostersRepo.create(),208 controller = Controller.create({}, repo, {}, false);209 await repo.add(imposterize(first));210 await repo.add(imposterize(second));211 await controller.del(Request.to('/imposters'), response);212 assert.deepEqual(response.body, { imposters: ['firstJSON', 'secondJSON'] });213 assert.ok(first.toJSON.wasCalledWith({ replayable: true, removeProxies: false }), first.toJSON.message());214 assert.ok(second.toJSON.wasCalledWith({ replayable: true, removeProxies: false }), second.toJSON.message());215 });216 it('should send default JSON for all imposters if replayable is false on querystring', async function () {217 const first = { port: 1, stop: stopMock(), toJSON: mock().returns(Promise.resolve('firstJSON')) },218 second = { port: 2, stop: stopMock(), toJSON: mock().returns(Promise.resolve('secondJSON')) },219 repo = ImpostersRepo.create(),220 controller = Controller.create({}, repo, {}, false);221 await repo.add(imposterize(first));222 await repo.add(imposterize(second));223 await controller.del(Request.to('/imposters?replayable=false'), response);224 assert.ok(first.toJSON.wasCalledWith({ replayable: false, removeProxies: false }), first.toJSON.message());225 assert.ok(second.toJSON.wasCalledWith({ replayable: false, removeProxies: false }), second.toJSON.message());226 });227 it('should send removeProxies JSON for all imposters if querystring present', async function () {228 const first = { port: 1, stop: mock(), toJSON: mock().returns(Promise.resolve('firstJSON')) },229 second = { port: 2, stop: mock(), toJSON: mock().returns(Promise.resolve('secondJSON')) },230 repo = ImpostersRepo.create(),231 controller = Controller.create({}, repo, {}, false);232 await repo.add(imposterize(first));233 await repo.add(imposterize(second));234 await controller.del(Request.to('/imposters?removeProxies=true'), response);235 assert.ok(first.toJSON.wasCalledWith({ replayable: true, removeProxies: true }),236 first.toJSON.message());237 assert.ok(second.toJSON.wasCalledWith({ replayable: true, removeProxies: true }),238 second.toJSON.message());239 });240 });241 describe('#put', function () {242 let request, logger, Protocol;243 beforeEach(function () {244 request = { body: {}, socket: { remoteAddress: 'host', remotePort: 'port' } };245 logger = FakeLogger.create();246 Protocol = {247 name: 'http',248 Validator: {249 create: mock().returns({ validate: mock().returns(Promise.resolve({ isValid: true, errors: [] })) })250 }251 };252 });253 it('should return a 400 if the "imposters" key is not present', async function () {254 const existingImposter = { port: 0, stop: mock() },255 repo = ImpostersRepo.create(),256 controller = Controller.create({ http: Protocol }, repo, logger, false);257 request.body = {};258 await repo.add(imposterize(existingImposter));259 await controller.put(request, response);260 assert.strictEqual(response.statusCode, 400);261 assert.deepEqual(response.body, {262 errors: [{263 code: 'bad data',264 message: "'imposters' is a required field"265 }]266 });267 const allImposters = await repo.all();268 const ports = allImposters.map(imposter => imposter.port);269 assert.deepEqual(ports, [0]);270 });271 it('should return an empty array if no imposters provided', async function () {272 const existingImposter = { port: 0, stop: mock() },273 repo = ImpostersRepo.create(),274 controller = Controller.create({ http: Protocol }, repo, logger, false);275 request.body = { imposters: [] };276 await repo.add(imposterize(existingImposter));277 await controller.put(request, response);278 assert.deepEqual(response.body, { imposters: [] });279 const allImposters = await repo.all();280 assert.deepEqual(allImposters, []);281 });282 it('should return imposter list JSON for all imposters', async function () {283 let creates = 0;284 const first = { port: 1, toJSON: mock().returns(Promise.resolve({ first: true })) },285 second = { port: 2, toJSON: mock().returns(Promise.resolve({ second: true })) },286 imposters = [first, second],287 impostersRepo = ImpostersRepo.create(),288 controller = Controller.create({ http: Protocol }, impostersRepo, logger, false);289 Protocol.createImposterFrom = creationRequest => {290 const result = imposters[creates];291 result.creationRequest = creationRequest;292 creates += 1;293 return result;294 };295 request.body = { imposters: [{ protocol: 'http' }, { protocol: 'http' }] };296 await controller.put(request, response);297 assert.deepEqual(response.body, { imposters: [{ first: true }, { second: true }] });298 assert.ok(first.toJSON.wasCalledWith({ list: true }), first.toJSON.message());299 assert.ok(second.toJSON.wasCalledWith({ list: true }), second.toJSON.message());300 });301 it('should replace imposters list', async function () {302 let creates = 0;303 const oldImposter = { port: 0, stop: mock() },304 repo = ImpostersRepo.create(),305 first = { toJSON: mock().returns(Promise.resolve({ first: true })), port: 1 },306 second = { toJSON: mock().returns(Promise.resolve({ second: true })), port: 2 },307 impostersToCreate = [first, second],308 controller = Controller.create({ http: Protocol }, repo, logger, false);309 Protocol.createImposterFrom = creationRequest => {310 const result = impostersToCreate[creates];311 result.creationRequest = creationRequest;312 creates += 1;313 return result;314 };315 request.body = { imposters: [{ protocol: 'http' }, { protocol: 'http' }] };316 await repo.add(imposterize(oldImposter));317 await controller.put(request, response);318 const allImposters = await repo.all();319 assert.deepEqual(allImposters, [first, second]);320 assert.ok(first.toJSON.wasCalledWith({ list: true }), first.toJSON.message());321 assert.ok(second.toJSON.wasCalledWith({ list: true }), second.toJSON.message());322 });323 it('should return a 400 for any invalid imposter', async function () {324 const controller = Controller.create({ http: Protocol }, { imposters: {} }, logger, false);325 request.body = { imposters: [{ protocol: 'http' }, {}] };326 await controller.put(request, response);327 assert.strictEqual(response.statusCode, 400);328 assert.deepEqual(response.body, {329 errors: [{330 code: 'bad data',331 message: "'protocol' is a required field"332 }]333 });334 });335 it('should return a 403 for insufficient access on any imposter', async function () {336 let creates = 0;337 const imposters = {338 deleteAll: mock().returns(Promise.resolve(true)),339 imposters: {}340 },341 controller = Controller.create({ http: Protocol }, imposters, logger, false);342 Protocol.createImposterFrom = () => {343 creates += 1;344 if (creates === 2) {345 return Promise.reject({346 code: 'insufficient access',347 key: 'value'348 });349 }350 else {351 return Promise.resolve({});352 }353 };354 request.body = { imposters: [{ protocol: 'http' }, { protocol: 'http' }] };355 await controller.put(request, response);356 assert.strictEqual(response.statusCode, 403);357 assert.deepEqual(response.body, {358 errors: [{359 code: 'insufficient access',360 key: 'value'361 }]362 });363 });364 });...
Using AI Code Generation
1var impostersRepo = require('mountebank').impostersRepo;2impostersRepo.add({ port: 3000 });3impostersRepo.add({ port: 3001 });4impostersRepo.add({ port: 3002 });5impostersRepo.add({ port: 3003 });6impostersRepo.add({ port: 3004 });7var impostersRepo = require('mountebank').impostersRepo;8impostersRepo.add({ port: 3000 });9impostersRepo.add({ port: 3001 });10impostersRepo.add({ port: 3002 });11impostersRepo.add({ port: 3003 });12impostersRepo.add({ port: 3004 });13 at Object.<anonymous> (C:\Users\test\test.js:2:18)14 at Module._compile (module.js:570:32)15 at Object.Module._extensions..js (module.js:579:10)16 at Module.load (module.js:487:32)17 at tryModuleLoad (module.js:446:12)18 at Function.Module._load (module.js:438:3)19 at Function.Module.runMain (module.js:604:10)20 at startup (bootstrap_node.js:158:16)21 at Object.<anonymous> (C:\Users\test\test.js:2:18)22 at Module._compile (module.js:570:32)23 at Object.Module._extensions..js (module.js:579:10)24 at Module.load (module.js:487:32)25 at tryModuleLoad (module.js:446:12)26 at Function.Module._load (module.js:438:3)27 at Function.Module.runMain (module.js:604:10)28 at startup (bootstrap_node.js:158:16)
Using AI Code Generation
1var mb = require('mountebank');2var impostersRepo = mb.create({port: 2525}).imposters;3var mb = require('mountebank');4var impostersRepo = mb.create({port: 2525}).imposters;5var mb = require('mountebank');6var impostersRepo = mb.create({port: 2525}).imposters;7var mb = require('mountebank');8var impostersRepo = mb.create({port: 2525}).imposters;9var mb = require('mountebank');10var impostersRepo = mb.create({port: 2525}).imposters;11var mb = require('mountebank');12var impostersRepo = mb.create({port: 2525}).imposters;13var mb = require('mountebank');14var impostersRepo = mb.create({port: 2525}).imposters;15var mb = require('mountebank');16var impostersRepo = mb.create({port: 2525}).imposters;17var mb = require('mountebank');18var impostersRepo = mb.create({port: 2525}).imposters;19var mb = require('mountebank');20var impostersRepo = mb.create({port: 2525}).imposters;21var mb = require('mountebank');22var impostersRepo = mb.create({port: 2525}).imposters;23var mb = require('mountebank');24var impostersRepo = mb.create({port: 2525}).imposters;25var mb = require('mountebank');26var impostersRepo = mb.create({port
Using AI Code Generation
1var mb = require('mountebank');2var impostersRepo = mb.createImpostersRepository();3 {4 {5 {6 is: {7 headers: {8 },9 }10 }11 }12 }13];14impostersRepo.add(imposters, function () {15 console.log('Added imposters');16});17impostersRepo.all(function (error, imposters) {18 console.log('Retrieved imposters: ', imposters);19});20impostersRepo.remove(imposters, function () {21 console.log('Removed imposters');22});23impostersRepo.all(function (error, imposters) {24 console.log('Retrieved imposters: ', imposters);25});26var mb = require('mountebank');27 {28 {29 {30 equals: {31 }32 }33 {34 is: {35 headers: {36 },37 body: {38 }39 }40 }41 }42 }43];44mb.createImposter(2525, imposters);45 at Object.exports.validate (C:\Users\test\AppData\Roaming46 at Object.exports.validate (C:\Users\test\AppData\Roaming
Using AI Code Generation
1var mb = require('mountebank');2var impostersRepo = mb.createImpostersRepository();3var imposters = impostersRepo.all();4console.log(imposters);5var imposter = {6 {7 { equals: { method: 'GET', path: '/test' } }8 { is: { body: 'Hello world!' } }9 }10};11impostersRepo.add(imposter);12imposters = impostersRepo.all();13console.log(imposters);14imposter = impostersRepo.get(4545);15console.log(imposter);16impostersRepo.del(4545);17impostersRepo.delAll();18[ { port: 4545,19 _links: { self: [Object] } } ]20{ port: 4545,21 stubs: [ { predicates: [Object], responses: [Object] } ],22 _links: { self: { href: '/imposters/4545' } } }
Using AI Code Generation
1const mb = require('mountebank');2const impostersRepo = mb.create();3const imposter = {4 {5 {6 is: {7 headers: { 'Content-Type': 'application/json' },8 body: { foo: 'bar' }9 }10 }11 }12};13impostersRepo.add(imposter).then(function (createdImposter) {14 console.log(createdImposter.port);15 impostersRepo.remove(createdImposter.port).then(function () {16 console.log('Imposter removed');17 });18});19{20 {21 {22 "is": {23 "headers": {24 },25 "body": { "foo": "bar"
Using AI Code Generation
1var impostersRepo = require('mountebank').create().impostersRepo;2var imposters = impostersRepo.all();3var imposter = imposters[0];4imposter.stub({responses: [{is: {body: 'Hello World'}}]});5imposter.stubs[0].predicate.exactMatch({method: 'GET', path: '/test'});6imposter.stubs[0].responses[0].is.statusCode = 200;7var impostersRepo = require('mountebank').create().impostersRepo;8var imposter = impostersRepo.add({protocol: 'http', port: 3000});9imposter.stub({responses: [{is: {body: 'Hello World'}}]});10imposter.stubs[0].predicate.exactMatch({method: 'GET', path: '/test'});11imposter.stubs[0].responses[0].is.statusCode = 200;12var impostersRepo = require('mountebank').create().impostersRepo;13var imposter = impostersRepo.add({protocol: 'http', port: 3000});14imposter.stub({responses: [{is: {body: 'Hello World'}}]});15imposter.stubs[0].predicate.exactMatch({method: 'GET', path: '/test'});16imposter.stubs[0].responses[0].is.statusCode = 200;17var impostersRepo = require('mountebank').create().impostersRepo;18var imposter = impostersRepo.add({protocol: 'http', port: 3000});19imposter.stub({responses: [{is: {body: 'Hello World'}}]});20imposter.stubs[0].predicate.exactMatch({method: 'GET', path: '/test'});21imposter.stubs[0].responses[0].is.statusCode = 200;22var impostersRepo = require('mountebank').create().impostersRepo;23var imposter = impostersRepo.add({protocol: 'http', port: 3000});24imposter.stub({responses:
Using AI Code Generation
1var mb = require('mountebank-client');2var imposters = mb.create({ port: 2525, protocol: 'http' });3var impostersRepo = imposters.getImposters();4var isCreated = impostersRepo.create({ protocol: 'http', port: 3000, stubs: [{ responses: [{ is: { body: 'Hello, World!' } }] }] });5console.log(isCreated);6var mb = require('mountebank-client');7var imposters = mb.create({ port: 2525, protocol: 'http' });8var impostersRepo = imposters.getImposters();9var isCreated = impostersRepo.create({ protocol: 'http', port: 3000, stubs: [{ responses: [{ is: { body: 'Hello, World!' } }] }] });10console.log(isCreated);11var mb = require('mountebank-client');12var imposters = mb.create({ port: 2525, protocol: 'http' });13var impostersRepo = imposters.getImposters();14var isCreated = impostersRepo.create({ protocol: 'http', port: 3000, stubs: [{ responses: [{ is: { body: 'Hello, World!' } }] }] });15console.log(isCreated);16var mb = require('mountebank-client');17var imposters = mb.create({ port: 2525, protocol: 'http' });18var impostersRepo = imposters.getImposters();19var isCreated = impostersRepo.create({ protocol: 'http', port: 3000, stubs: [{ responses: [{ is: { body: 'Hello, World!' } }] }] });20console.log(isCreated);21var mb = require('mountebank-client');22var imposters = mb.create({ port: 2525, protocol: 'http' });23var impostersRepo = imposters.getImposters();24var isCreated = impostersRepo.create({ protocol: 'http', port: 3000, stubs: [{ responses: [{ is: { body: 'Hello
Using AI Code Generation
1const mb = require('mountebank');2const impostersRepo = mb.createImpostersRepo();3mb.createImpostersRepo() is a function that returns a promise. The promise resolves to an object that contains the following functions:4const mb = require('mountebank');5const impostersRepo = mb.createImpostersRepo();6impostersRepo.add({ port: 3000 })7 .then(() => impostersRepo.get(3000))8 .then(response => {9 });10const mb = require('mountebank');11const impostersRepo = mb.createImpostersRepo();12impostersRepo.add({ port: 3000 })13 .then(() => impostersRepo.add({ port: 3001 }))14 .then(() => impostersRepo.getAll())15 .then(response => {16 });17const mb = require('mountebank');18const impostersRepo = mb.createImpostersRepo();19impostersRepo.add({ port: 3000 })20 .then(() => impostersRepo.add({ port: 3001 }))21 .then(() => impostersRepo.remove(3000))22 .then(() => impostersRepo.countAll())23 .then(response => {24 });25const mb = require('
Using AI Code Generation
1var newImposter = {2 {3 {4 is: {5 headers: { 'Content-Type': 'application/json' },6 body: { status: 'ok' }7 }8 }9 }10};11impostersRepo.add(newImposter, function (error, imposter) {12 if (error) {13 console.error(error);14 } else {15 console.log('imposter created', imposter);16 }17});18impostersRepo.remove(4545, function (error) {19 if (error) {20 console.error(error);21 } else {22 console.log('imposter removed');23 }24});25impostersRepo.get(4545, function (error, imposter) {26 if (error) {27 console.error(error);28 } else {29 console.log('imposter', imposter);30 }31});32impostersRepo.all(function (error, imposters) {33 if (error) {34 console.error(error);35 } else {36 console.log('imposters', imposters);37 }38});39impostersRepo.requests(4545, function (error, requests) {40 if (error) {41 console.error(error);42 } else {43 console.log('requests', requests);44 }45});46impostersRepo.reset(4545, function (error) {47 if (error) {48 console.error(error);49 } else {50 console.log('requests reset');51 }52});53impostersRepo.addStub(4545, { responses: [{ is: { statusCode: 200 } }] }, function (error, imposter) {54 if (error) {55 console.error(error);56 } else {57 console.log('stub added', imposter);58 }59});60impostersRepo.removeStub(4545, 0, function (error, imposter) {61 if (error) {62 console.error(error);63 } else
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!!