How to use createHttpReqOptions method in apimocker

Best JavaScript code snippet using apimocker

test-functional.js

Source:test-functional.js Github

copy

Full Screen

...13 port: 7879,14 method: method || 'GET',15 path16});17const createHttpPostOptions = (path, data) => _.extend(createHttpReqOptions(path, 'POST'), {18 headers: {19 'Content-Type': 'application/json',20 'Content-Length': data.length21 }22});23const MOCK_PORT = 7881;24const verifyResponseHeaders = (httpReqOptions, expected, done) => {25 const req = http.request(httpReqOptions, (res) => {26 res.setEncoding('utf8');27 res.on('data', () => {28 // console.log('Response headers: ' + JSON.stringify(res.headers));29 const expectedKeys = _.keys(expected);30 _.each(expectedKeys, (key) => {31 expect(res.headers[key]).to.equal(expected[key]);32 });33 done();34 });35 });36 req.end();37};38const verifyResponseBody = (httpReqOptions, postData, expected, done) => {39 const req = http.request(httpReqOptions, (res) => {40 res.setEncoding('utf8');41 res.on('data', (chunk) => {42 // console.log(chunk);43 expect(res.statusCode).to.be.lessThan(400);44 expect(JSON.parse(chunk)).to.deep.equal(expected);45 if (done) {46 done();47 }48 });49 });50 if (postData) {51 req.write(postData);52 }53 req.end();54};55const clearDirSync = (dirname) => {56 _.each(fs.readdirSync(dirname), (fname) => {57 fs.unlinkSync(pathJoin(dirname, fname));58 });59};60describe('Functional tests using an http client to test "end-to-end": ', () => {61 describe('apimocker server:', () => {62 let mocker;63 let testEndpoint;64 before((done) => {65 const options = {66 quiet: true,67 mockDirectory: './samplemocks/',68 proxyURL: `http://localhost:${MOCK_PORT}`69 };70 mocker = apiMocker.createServer(options).setConfigFile('test/test-config.json');71 mocker.start(null);72 testEndpoint = http73 .createServer((req, res) => {74 if (req.url === '/non-mocked') {75 res.writeHead(200, { 'Content-Type': 'application/json' });76 res.end(JSON.stringify({ data: 'real' }));77 } else {78 res.writeHead(404);79 res.end();80 }81 })82 .listen(MOCK_PORT, done);83 });84 after((done) => {85 mocker.stop(done);86 testEndpoint.close();87 });88 describe('basic requests: ', () => {89 it('returns correct data for basic get request', (done) => {90 const reqOptions = createHttpReqOptions('/first');91 verifyResponseBody(reqOptions, null, { king: 'greg' }, done);92 });93 it('Returns correct body data', (done) => {94 const reqOptions = createHttpReqOptions('/raw');95 verifyResponseBody(reqOptions, null, { text: 'Good Job!' }, done);96 });97 it('Returns correct body data from message', (done) => {98 const reqOptions = createHttpReqOptions('/raw/template/ATestHashToReturn');99 verifyResponseBody(reqOptions, null, { text: 'ATestHashToReturn' }, done);100 });101 it('returns correct data for basic post request', (done) => {102 const reqOptions = createHttpReqOptions('/nested/ace');103 reqOptions.method = 'POST';104 verifyResponseBody(reqOptions, null, { ace: 'greg' }, done);105 });106 it('returns correct data for post to path with mockFile varying on verb', (done) => {107 const reqOptions = createHttpReqOptions('/royals');108 reqOptions.method = 'POST';109 verifyResponseBody(reqOptions, null, { king: 'greg' }, done);110 });111 it('returns correct data for get to path with mockFile varying on verb', (done) => {112 const reqOptions = createHttpReqOptions('/royals');113 verifyResponseBody(reqOptions, null, { ace: 'greg' }, done);114 });115 it('Returns data in template from the route', (done) => {116 const reqOptions = createHttpReqOptions('/template/john/4');117 verifyResponseBody(reqOptions, null, { name: 'john', number: 4 }, done);118 });119 it('returns correct data for get to templateSwitch substituting GET params into mockFile ', (done) => {120 const reqOptions = createHttpReqOptions(121 '/templateSwitchGetParams?appID=123456789&appName=myAppName&userName=MyName&userAge=21'122 );123 const expected = {124 appID: 123456789,125 appName: 'myAppName',126 userName: 'MyName',127 userAge: 21128 };129 verifyResponseBody(reqOptions, null, expected, done);130 });131 it('returns correct data for post to templateSwitch substituting POST data parsed using jsonPath into mockFile', (done) => {132 const postData = '{ "data": { "appID": 123456789, "appName": "myAppName", "user": { "userName": "MyName", "userAge": 21 } } }';133 const postOptions = createHttpPostOptions('/templateSwitchPostJsonPath', postData);134 const expected = {135 appID: 123456789,136 appName: 'myAppName',137 userName: 'MyName',138 userAge: 21139 };140 verifyResponseBody(postOptions, postData, expected, done);141 });142 it('returns correct data for an alternate path', (done) => {143 const reqOptions = createHttpReqOptions('/1st');144 verifyResponseBody(reqOptions, null, { king: 'greg' }, done);145 });146 });147 describe('content type: ', () => {148 it('returns a custom content type', (done) => {149 const reqOptions = createHttpReqOptions('/first');150 verifyResponseHeaders(reqOptions, { 'content-type': 'foobar' }, done);151 });152 it('returns correct content-type for json response, with nested path', (done) => {153 const reqOptions = createHttpReqOptions('/nested/ace');154 verifyResponseHeaders(155 reqOptions,156 { 'content-type': 'application/json; charset=UTF-8' },157 done158 );159 });160 it('returns correct content-type for xml response', (done) => {161 const reqOptions = createHttpReqOptions('/var/123');162 verifyResponseHeaders(reqOptions, { 'content-type': 'application/xml' }, done);163 });164 });165 describe('switch on request param: ', () => {166 it('returns correct file for switch param in json request', (done) => {167 const postData = '{"customerId": 1234}';168 const postOptions = createHttpPostOptions('/nested/ace', postData);169 const expected = {170 ace: 'greg',171 note: 'request contained customerId = 1234'172 };173 verifyResponseBody(postOptions, postData, expected, done);174 });175 it('returns base file when no match for switch param in json request', (done) => {176 const postData = '{"customerId": 124}';177 const postOptions = createHttpPostOptions('/nested/ace', postData);178 const expected = {179 ace: 'greg'180 };181 verifyResponseBody(postOptions, postData, expected, done);182 });183 it('returns base file when no switch param passed in json request', (done) => {184 const postData = '{"phonenumber": 124}';185 const postOptions = createHttpPostOptions('/nested/ace', postData);186 const expected = {187 ace: 'greg'188 };189 verifyResponseBody(postOptions, postData, expected, done);190 });191 it('returns correct file for switch param in query string', (done) => {192 const reqOptions = createHttpReqOptions('/nested/ace?customerId=1234');193 const expected = {194 ace: 'greg',195 note: 'request contained customerId = 1234'196 };197 verifyResponseBody(reqOptions, null, expected, done);198 });199 it('returns correct httpStatus when switches match', (done) => {200 stRequest201 .post('/login')202 .set('Content-Type', 'application/json')203 .send('{"userId": "user1", "password": "good"}')204 .expect(200, done);205 });206 it('returns correct httpStatus when switch does not match, with contentType set', (done) => {207 stRequest208 .post('/login')209 .set('Content-Type', 'application/json')210 .send('{"userId": "user1", "password": "bad"}')211 .expect(401, done);212 });213 it('returns correct httpStatus when switch does not match', (done) => {214 stRequest215 .post('/login')216 .send('{"userId": "user1", "password": "bad"}')217 .expect(401, done);218 });219 it('returns 404 when switch does not match and no httpStatus was set', (done) => {220 stRequest221 .post('/verify')222 .send('{"foo": "bar"}')223 .expect(404, done);224 });225 });226 describe('jsonPath switch response', () => {227 it('returns proper single object from mockFile', (done) => {228 const reqOptions = createHttpReqOptions('/users/1');229 verifyResponseBody(reqOptions, null, { name: 'Han Solo', role: 'pilot', id: 1 }, done);230 });231 it('returns proper array of results', (done) => {232 const reqOptions = createHttpReqOptions('/users/role/droid');233 const expected = [234 {235 name: 'C3P0',236 role: 'droid',237 id: 3238 },239 {240 name: 'R2D2',241 role: 'droid',242 id: 4243 }244 ];245 verifyResponseBody(reqOptions, null, expected, done);246 });247 });248 describe('http status: ', () => {249 it('returns 404 for incorrect path', (done) => {250 stRequest251 .get('/badurl')252 .expect(404)253 .end(() => {254 // console.log('got a 404 as expected');255 done();256 });257 });258 it('returns httpStatus of 200 if not set', (done) => {259 stRequest.get('/first').expect(200, done);260 });261 it('returns httpStatus specified in config file, when contentType is passed in', (done) => {262 stRequest.put('/protected').expect(403, done);263 });264 it('returns httpStatus 204 specified in config file', (done) => {265 stRequest.delete('/second').expect(204, done);266 });267 it('returns httpStatus 404 if no mockFile is set for a web service', (done) => {268 stRequest.get('/noMockFile').expect(404, done);269 });270 it('returns specified httpStatus even if mockFile is set incorrectly and no contentType is configured', (done) => {271 stRequest.get('/missingMockFile').expect(203, done);272 });273 });274 describe('http headers: ', () => {275 it('returns the headers as specified in the config file', (done) => {276 const reqOptions = createHttpReqOptions('/firstheaders');277 verifyResponseHeaders(278 reqOptions,279 {280 'x-requested-by':281 '4c2df03a17a803c063f21aa86a36f6f55bdde1f85b89e49ee1b383f281d18c09c2ba30654090df3531cd2318e3c',282 dummyheader: 'dummyvalue',283 'content-type': 'foobar'284 },285 done286 );287 });288 it('allows domains specified in config file', (done) => {289 const reqOptions = createHttpReqOptions('/first');290 verifyResponseHeaders(reqOptions, { 'access-control-allow-origin': 'abc' }, done);291 });292 it('allows headers as specified in config file', (done) => {293 const reqOptions = createHttpReqOptions('/first');294 verifyResponseHeaders(295 reqOptions,296 { 'access-control-allow-headers': 'Content-Type,my-custom-header' },297 done298 );299 });300 it('sets Access-Control-Allow-Credentials header if corsCredentials option is set', (done) => {301 const reqOptions = createHttpReqOptions('/first');302 verifyResponseHeaders(reqOptions, { 'access-control-allow-credentials': 'true' }, done);303 });304 });305 describe('proxy: ', () => {306 it('forwards get request to non-mocked endpoint', (done) => {307 stRequest.get('/non-mocked').expect(200, { data: 'real' }, done);308 });309 it('forwards post request to non-mocked endpoint', (done) => {310 stRequest311 .post('/non-mocked')312 .set('Content-Type', 'application/json')313 .send({ foo: 'bar' })314 .expect(200, { data: 'real' }, done);315 });316 });317 describe('admin functions for on-the-fly configuration', () => {318 // function reloadConfigFile(mocker, done) {319 // mocker.setConfigFile("test/test-config.json");320 // var req, reqOptions = createHttpReqOptions();321 // reqOptions.path = "/admin/reload";322 // req = http.request(reqOptions, function(res) {323 // res.setEncoding('utf8');324 // res.on('data', function () {325 // expect(res.statusCode).to.equal(200);326 // if (done) {327 // done();328 // }329 // });330 // });331 // req.end();332 // }333 it('returns correct mock file after admin/setMock was called', (done) => {334 const postData = { verb: 'get', serviceUrl: 'third', mockFile: 'king.json' };335 // const postOptions = createHttpPostOptions('/admin/setMock', postData);336 // const expected = {337 // verb: 'get',338 // serviceUrl: 'third',339 // mockFile: 'king.json',340 // httpStatus: 200,341 // };342 // verifyResponseBody(postOptions, postData, expected);343 // verifyResponseBody(createHttpReqOptions('/third'), null, {king: 'greg'}, done);344 stRequest345 .post('/admin/setMock')346 .set('Content-Type', 'application/json')347 .send(postData)348 .expect(200, () => {349 stRequest.get('/third').expect(200, { king: 'greg' }, done);350 });351 });352 it('returns correct mock file with http status code after admin/setMock was called', (done) => {353 const postData = {354 verb: 'post',355 serviceUrl: 'third',356 mockFile: 'king.json',357 httpStatus: 201358 };359 // const postOptions = createHttpPostOptions('/admin/setMock', postData);360 // const expected = {361 // verb: 'post',362 // serviceUrl: 'third',363 // mockFile: 'king.json',364 // httpStatus: 201,365 // };366 stRequest367 .post('/admin/setMock')368 .set('Content-Type', 'application/json')369 .send(postData)370 .expect(200, () => {371 stRequest.post('/third').expect(201, { king: 'greg' }, done);372 });373 });374 // it('returns 404 for incorrect path after reload was called', function(done) {375 // verifyResponseBody(postOptions, postData, expected);376 // verifyResponseBody(createHttpReqOptions('/third'), null, {king: 'greg'});377 // reloadConfigFile(mocker);378 // verifyResponseStatus(createHttpReqOptions('/third'), null, 404, done);379 // });380 // TODO: Fix this test... it fails intermittently, due to timing problems.381 it.skip('returns correct mock file after admin/setMock was called twice', (done) => {382 // verifyResponseBody(postOptions, postData, expected);383 // verifyResponseBody(createHttpReqOptions('/third'), null, {king: 'greg'});384 // // change route, and verify again385 // verifyResponseBody(postOptions, postData, expected);386 // verifyResponseBody(createHttpReqOptions('/third'), null, {ace: 'greg'}, done);387 stRequest388 .post('/admin/setMock')389 .set('Content-Type', 'application/json')390 // .send(postData)391 .expect(200, () => {392 stRequest.get('/third').expect(200, { kingyy: 'greg' }, () => {393 stRequest394 .post('/admin/setMock')395 .set('Content-Type', 'application/json')396 .send({ verb: 'get', serviceUrl: 'third', mockFile: 'king.json' })397 .expect(200, () => {398 stRequest.get('/third').expect(200, { ace: 'greg' }, done);399 });400 });401 });402 });403 });404 });405 describe('with custom basepath: ', () => {406 let mocker;407 before((done) => {408 const options = {409 quiet: true,410 mockDirectory: './samplemocks/',411 proxyURL: `http://localhost:${MOCK_PORT}`,412 basepath: '/apimocker'413 };414 mocker = apiMocker.createServer(options).setConfigFile('test/test-config.json');415 mocker.start(null, done);416 });417 it('uses custom basepath if specified', (done) => {418 stRequest.get('/apimocker/nested/ace').expect(200, { ace: 'greg' }, done);419 });420 after((done) => {421 mocker.stop(done);422 });423 });424});425describe('apimocker with custom middleware: ', () => {426 let customMiddleware;427 let mocker;428 before((done) => {429 customMiddleware = (req, res, next) => {430 res.header('foo', 'bar');431 next();432 };433 mocker = apiMocker434 .createServer({ quiet: true, mockDirectory: './samplemocks/' })435 .setConfigFile('test/test-config.json');436 mocker.middlewares.unshift(customMiddleware);437 mocker.start(null, done);438 });439 it('uses custom middleware if added by user', (done) => {440 const reqOptions = createHttpReqOptions('/first');441 verifyResponseHeaders(reqOptions, { foo: 'bar' }, done);442 });443 after((done) => {444 mocker.stop(done);445 });446});447describe('apimocker with file upload: ', () => {448 let mocker;449 before((done) => {450 const config = {451 quiet: true,452 mockDirectory: './uploads/',453 uploadRoot: './uploads/'454 };...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run apimocker automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful