How to use parseJsonBody method in Cypress

Best JavaScript code snippet using cypress

test.js

Source:test.js Github

copy

Full Screen

...71 assert(72 headers['content-type'] === contentType ||73 headers['content-type'].startsWith(contentType + ';'));74}75function parseJsonBody(headers, body) {76 assertContentType(headers, 'application/json');77 return JSON.parse(body);78}79describe('bookstore', function() {80 var server;81 before(function(done) {82 // Initialize bookstore without Swagger UI and in quiet mode.83 var options = {84 log: false,85 ui: false,86 };87 server = bookstore(options).listen(PORT, '0.0.0.0', function() {88 done();89 });90 });91 after(function(done) {92 if (server) {93 server.close(done);94 } else {95 done();96 }97 });98 beforeEach(function(done) {99 // Delete all shelves.100 // In each turn we list all remaining shelves and delete one of them.101 // The algorithm terminates when an empty list of shelves is returned.102 function loop() {103 request('GET', '/shelves', null, function(res, body) {104 assert.equal(res.statusCode, 200, 'list shelves didn\'t return 200');105 var json = parseJsonBody(res.headers, body);106 var shelves = json.shelves;107 if (shelves && shelves.length > 0) {108 request('DELETE', '/' + shelves[0].name, null, function(res, body) {109 assert.equal(res.statusCode, 204, 'DELETE valid shelf didn\'t return 204');110 assert.equal(body, null);111 // Proceed deleting the next shelf.112 loop();113 });114 } else {115 // All shelves have been deleted.116 done();117 }118 });119 }120 // Initiate the deletion sequence.121 loop();122 });123 function unsupported(path, tests) {124 for (var method in tests) {125 var body = tests[method];126 it(method + ' is not supported', function(done) {127 request(method, path, body, function(res, _) {128 assert.equal(res.statusCode, 404);129 done();130 });131 });132 }133 }134 function createShelf(theme, done) {135 request('POST', '/shelves', JSON.stringify({136 theme: theme137 }), function(res, body) {138 assert.strictEqual(res.statusCode, 200);139 done(parseJsonBody(res.headers, body));140 });141 }142 function createBook(shelf, author, title, done) {143 request('POST', '/' + shelf + '/books', JSON.stringify({144 author: author,145 title: title146 }), function(res, body) {147 assert.strictEqual(res.statusCode, 200);148 done(parseJsonBody(res.headers, body));149 });150 }151 describe('/', function() {152 it('GET returns welcome page', function(done) {153 request('GET', '/', null, function(res, body) {154 assert.strictEqual(155 res.statusCode, 200,156 'fetching welcome page did not return HTTP 200');157 assertContentType(res.headers, 'text/html');158 done();159 });160 });161 unsupported('/', {162 PUT: '{}',163 POST: '{}',164 PATCH: '{}',165 DELETE: null,166 });167 });168 describe('/shelves', function() {169 var fictionShelf = null;170 var fantasyShelf = null;171 beforeEach(function(done) {172 createShelf('Fiction', function(fiction) {173 fictionShelf = fiction;174 createShelf('Fantasy', function(fantasy) {175 fantasyShelf = fantasy;176 createBook(fiction.name, 'Neal Stephenson', 'Seveneves',177 function(seveneves) {178 createBook(fantasy.name, 'J. R. R. Tolkien',179 'The Lord of the Rings', function(lotr) {180 done();181 });182 });183 });184 });185 });186 it('GET returns list of shelves', function(done) {187 request('GET', '/shelves', null, function(res, body) {188 assert.equal(res.statusCode, 200, 'list shelves didn\'t return 200');189 var json = parseJsonBody(res.headers, body);190 assert.property(json, 'shelves');191 assert.isArray(json.shelves);192 json.shelves.forEach(function(shelf) {193 assert.property(shelf, 'name');194 assert.property(shelf, 'theme');195 assert.isString(shelf.name);196 assert.isString(shelf.theme);197 });198 assert.sameDeepMembers(json.shelves, [fictionShelf, fantasyShelf]);199 done();200 });201 });202 it('POST creates a new shelf', function(done) {203 request('POST', '/shelves', JSON.stringify({204 theme: 'Nonfiction'205 }), function(res, body) {206 assert.equal(res.statusCode, 200, 'create shelf didn\'t return 200');207 var shelf = parseJsonBody(res.headers, body);208 assert.property(shelf, 'name');209 assert.match(shelf.name, /^shelves\/[0-9]+$/);210 assert.propertyVal(shelf, 'theme', 'Nonfiction');211 done();212 });213 });214 unsupported('/shelves', {215 PUT: '{}',216 PATCH: '{}',217 DELETE: null218 });219 });220 describe('/shelves/{shelf}', function() {221 var testShelf = null;222 beforeEach('create test shelf', function(done) {223 createShelf('Poetry', function(shelf) {224 assert.propertyVal(shelf, 'theme', 'Poetry');225 testShelf = shelf;226 done();227 });228 });229 it('GET of a valid shelf returns shelf', function(done) {230 request('GET', '/' + testShelf.name, null, function(res, body) {231 assert.equal(res.statusCode, 200, 'GET valid shelf didn\'t return 200');232 var shelf = parseJsonBody(res.headers, body);233 assert.deepEqual(shelf, testShelf);234 done();235 });236 });237 it('GET of an invalid shelf returns 404', function(done) {238 request('GET', '/shelves/999999', null, function(res, body) {239 assert.equal(res.statusCode, 404, 'GET invalid shelf didn\'t return 404');240 var error = parseJsonBody(res.headers, body);241 assert.property(error, 'message');242 done();243 });244 });245 it('DELETE of a valid shelf deletes it', function(done) {246 request('DELETE', '/' + testShelf.name, null, function(res, body) {247 assert.equal(res.statusCode, 204, 'DELETE valid shelf didn\'t return 204');248 assert.equal(body, null);249 done();250 });251 });252 it('DELETE of an invalid shelf returns 404', function(done) {253 request('DELETE', '/' + testShelf.name, null, function(res, body) {254 assert.equal(res.statusCode, 204, 'DELETE valid shelf didn\'t return 204');255 assert.equal(body, null);256 // Try to delete the same shelf again.257 request('DELETE', '/' + testShelf.name, null, function(res, body) {258 assert.equal(res.statusCode, 404, 'DELETE invalid shelf didn\'t return 404');259 var error = parseJsonBody(res.headers, body);260 assert.property(error, 'message');261 done();262 });263 });264 });265 unsupported('/shelves/1', {266 PUT: '{}',267 POST: '{}',268 PATCH: '{}',269 });270 });271 describe('/shelves/{shelf}/books', function() {272 var testShelf = null;273 var testKnuth = null;274 var testStroustrup = null;275 beforeEach('create test shelf and book', function(done) {276 createShelf('Computers', function(shelf) {277 assert.propertyVal(shelf, 'theme', 'Computers');278 testShelf = shelf;279 createBook(shelf.name, 'Donald E. Knuth',280 'The Art of Computer Programming', function(book) {281 assert.propertyVal(book, 'author', 'Donald E. Knuth');282 assert.propertyVal(book, 'title', 'The Art of Computer Programming');283 testKnuth = book;284 createBook(shelf.name, 'Bjarne Stroustrup',285 'The C++ Programming Language', function(book) {286 assert.propertyVal(book, 'author', 'Bjarne Stroustrup');287 assert.propertyVal(book, 'title', 'The C++ Programming Language');288 testStroustrup = book;289 done();290 });291 });292 });293 });294 it('GET lists books on a valid shelf', function(done) {295 request('GET', '/' + testShelf.name + '/books', null, function(res, body) {296 assert.strictEqual(res.statusCode, 200, 'List books didn\'t return 200');297 var response = parseJsonBody(res.headers, body);298 assert.property(response, 'books');299 assert.isArray(response.books);300 assert.sameDeepMembers(response.books, [testKnuth, testStroustrup]);301 done();302 });303 });304 it('GET returns 404 for an invalid shelf', function(done) {305 request('GET', '/shelves/999999/books', null, function(res, body) {306 assert.strictEqual(res.statusCode, 404);307 var error = parseJsonBody(res.headers, body);308 assert.property(error, 'message');309 done();310 });311 });312 it('POST creates a new book in a valid shelf', function(done) {313 var practice = {314 author: 'Brian W. Kernighan, Rob Pike',315 title: 'The Practice of Programming'316 };317 request('POST', '/' + testShelf.name + '/books', JSON.stringify(practice),318 function(res, body) {319 assert.strictEqual(res.statusCode, 200);320 var book = parseJsonBody(res.headers, body);321 assert.propertyVal(book, 'author', 'Brian W. Kernighan, Rob Pike');322 assert.propertyVal(book, 'title', 'The Practice of Programming');323 assert.property(book, 'name');324 assert.isString(book.name);325 assert.match(book.name, /^shelves\/[0-9]+\/books\/[0-9]+$/);326 done();327 });328 });329 it('POST returns 404 for an invalid shelf', function(done) {330 var compilers = {331 author: 'Aho, Sethi, Ullman',332 title: 'Compilers'333 };334 request('POST', '/shelves/999999/books', JSON.stringify(compilers),335 function(res, body) {336 assert.strictEqual(res.statusCode, 404);337 var error = parseJsonBody(res.headers, body);338 assert.property(error, 'message');339 done();340 });341 });342 unsupported('/shelves/1/books', {343 PUT: '{}',344 PATCH: '{}',345 DELETE: null346 });347 });348 describe('/shelves/{shelf}/books/{book}', function() {349 var testYoga = null;350 var testSutras = null;351 var testBreathing = null;352 beforeEach('create test shelf and books', function(done) {353 createShelf('Yoga', function(shelf) {354 assert.propertyVal(shelf, 'theme', 'Yoga');355 testYoga = shelf;356 createBook(shelf.name, 'Patanjali', 'Yoga Sutras of Patanjali', function(book) {357 assert.propertyVal(book, 'author', 'Patanjali');358 assert.propertyVal(book, 'title', 'Yoga Sutras of Patanjali');359 testSutras = book;360 createBook(shelf.name, 'Donna Farhi', 'The breathing book', function(book) {361 assert.propertyVal(book, 'author', 'Donna Farhi');362 assert.propertyVal(book, 'title', 'The breathing book');363 testBreathing = book;364 done();365 });366 });367 });368 });369 it('GET of a valid book returns a book', function(done) {370 request('GET', '/' + testBreathing.name, null, function(res, body) {371 assert.strictEqual(res.statusCode, 200);372 var book = parseJsonBody(res.headers, body);373 assert.deepEqual(book, testBreathing);374 done();375 });376 });377 it('GET of a book on an invalid shelf returns 404', function(done) {378 request('GET', '/shelves/999999/books/5', null, function(res, body) {379 assert.strictEqual(res.statusCode, 404);380 var error = parseJsonBody(res.headers, body);381 assert.property(error, 'message');382 done();383 });384 });385 it('GET of an invalid book on valid shelf returns 404', function(done) {386 request('GET', '/' + testYoga.name + '/books/999999', null, function(res, body) {387 assert.strictEqual(res.statusCode, 404);388 var error = parseJsonBody(res.headers, body);389 assert.property(error, 'message');390 done();391 });392 });393 it('DELETE of a valid book deletes the book', function(done) {394 request('DELETE', '/' + testSutras.name, null, function(res, body) {395 assert.strictEqual(res.statusCode, 204);396 assert.equal(body, null);397 done();398 });399 });400 it('DELETE of a book on an invalid shelf returns 404', function(done) {401 request('DELETE', '/shelves/999999/books/5', null, function(res, body) {402 assert.strictEqual(res.statusCode, 404);403 var error = parseJsonBody(res.headers, body);404 assert.property(error, 'message');405 done();406 });407 });408 it('DELETE of an invalid book on a valid shelf returns 404', function(done) {409 // Delete the book as above.410 request('DELETE', '/' + testSutras.name, null, function(res, body) {411 assert.strictEqual(res.statusCode, 204);412 assert.equal(body, null);413 // Delete the same book again.414 request('DELETE', '/' + testSutras.name, null, function(res, body) {415 assert.strictEqual(res.statusCode, 404);416 var error = parseJsonBody(res.headers, body);417 assert.property(error, 'message');418 done();419 });420 });421 });422 unsupported('/shelves/1/books/2', {423 PUT: '{}',424 POST: '{}',425 PATCH: '{}',426 });427 });428 describe ('/version', function() {429 it('GET returns version', function(done) {430 request('GET', '/version', null, function(res, body) {431 assert.equal(res.statusCode, 200, '/version didn\'t return 200');432 var json = parseJsonBody(res.headers, body);433 assert.property(json, 'version');434 assert.isString(json.version);435 done();436 });437 });438 });439});440describe('bookstore-ui', function() {441 var server;442 before(function(done) {443 var swagger = require('../swagger.json');444 swagger.host = 'localhost:8080';445 // Initialize bookstore with Swagger UI and in quiet mode.446 var options = {447 log: false,448 swagger: swagger,449 };450 server = bookstore(options).listen(PORT, '0.0.0.0', function() {451 done();452 });453 });454 after(function(done) {455 if (server) {456 server.close(done);457 } else {458 done();459 }460 });461 describe('/docs', function() {462 it('GET on Swagger UI works', function(done) {463 request('GET', '/docs/', null, function(res, body) {464 assert.strictEqual(res.statusCode, 200,465 'fetching Swagger UI did not return HTTP 200');466 done();467 });468 });469 });470 describe('/api-docs', function() {471 it('GET returns swagger.json', function(done) {472 request('GET', '/api-docs', null, function(res, body) {473 assert.strictEqual(474 res.statusCode, 200, 'fetching swagger did not return HTTP 200');475 var swagger = parseJsonBody(res.headers, body);476 assert.propertyVal(swagger, 'swagger', '2.0');477 assert.deepPropertyVal(swagger, 'info.title', 'Bookstore');478 done();479 });480 });481 });...

Full Screen

Full Screen

wsod.js

Source:wsod.js Github

copy

Full Screen

...52 };53 logger.log( "debug2", 'WSOD token request ', options );54 request( options,55 function ( error, response, body ) {56 body = parseJsonBody( error, response, body );57 callback( error, response, body );58 }59 );60};61wsod.courses = function ( token, callback ) {62 var url = this.M_SERVICE_ROOT + "/me/courses?expand=course";63 var options = {64 uri: url,65 timeout: this.TIMEOUT,66 headers: { "x-authorization": "Access_Token access_token=" + token }67 };68 logger.log( "debug2", 'WSOD courses request ', options );69 request( options,70 function ( error, response, body ) {71 body = parseJsonBody( error, response, body );72 callback( error, response, body );73 }74 );75};76wsod.mapCourseId = function ( token, callback ) {77 var url = this.PH_SERVICE_ROOT + "/me/courseIdMap";78 var options = {79 uri: url,80 timeout: this.TIMEOUT,81 headers: { "x-authorization": "Access_Token access_token=" + token }82 };83 logger.log( "debug2", 'WSOD mapCourseId request ', options );84 request( options,85 function ( error, response, body ) {86 logger.log( "debug2", 'WSOD mapCourseId response ' + body );87 body = parseJsonBody( error, response, body );88 callback( error, response, body );89 }90 );91};92wsod.windmillTokenExchange = function ( moauth_access_token, callback ) {93 var url = this.PH_SERVICE_ROOT + "/windmilltoken";94 var options = {95 uri: url,96 timeout: this.TIMEOUT,97 headers: { "x-authorization": "Access_Token access_token=" + moauth_access_token }98 };99 logger.log( "debug2", 'WSOD windmillTokenExchange request', options );100 request( options,101 function ( error, response, body ) {102 body = parseJsonBody( error, response, body );103 callback( error, response, body );104 }105 );106};107wsod.cssOverrideRoot = function ( slug ) {108 return this.M_SERVICE_ROOT + "/clients/berlin." + slug + "/stylefiles";109};110// wsod.cssOverrideUrl = function(token, callback) {111// var url = this.M_SERVICE_ROOT + "/me/homenode";112// var self = this;113// request({114// uri:url,115// headers: { "x-authorization": "Access_Token access_token=" + token }116// },117// function(error, response, body) {118// if(!error && response.statusCode == 200) {119// body = parseJsonBody(error, response, body);120// var clientSortString = body.homeNode.clientSortString;121// var cssUrl = self.M_SERVICE_ROOT + "/clients/" + clientSortString + "/stylefiles/toolbar/inst-override.css";122// return callback(false, cssUrl);123// }124// logger.log("debug2", "Could not get clientSortString for token " + token);125// error = error || true;126// return callback(error, "");127// }128// );129// };130// http://peaks.eclg.org/get-meaffinityassertion131wsod.affinityAssertion = function ( token, callback ) {132 var url = this.PH_SERVICE_ROOT + "/me/affinityAssertion";133 var options = {134 uri: url,135 timeout: this.TIMEOUT,136 headers: { "x-authorization": "Access_Token access_token=" + token }137 };138 logger.log( "debug2", 'WSOD affinityAssertion request ', options );139 request( options,140 function ( error, response, body ) {141 body = parseJsonBody( error, response, body );142 callback( error, response, body );143 }144 );145};146wsod.affinitySession = function ( assertion, callback ) {147 var url = this.AFFINITY_PERSONA_ROOT + "/Affinity/v1/session?Authorization=" + assertion;148 var options = {149 uri: url,150 timeout: this.TIMEOUT151 };152 logger.log( "debug2", 'WSOD affinitySession request ', options );153 request( options,154 function ( error, response, body ) {155 body = parseJsonBody( error, response, body );156 callback( error, response, body );157 }158 );159};160wsod.affinityAvatarUrl = function ( token ) {161 var url = this.AFFINITY_PERSONA_ROOT + "/Affinity/v1/avatar/"162 + this.affinityIdFromToken( token ) + "?Authorization=" + token;163 return url;164}165/**166 * Given an affinity token return an Affinity Avatar URL wrapped in a callback167 * @param {string} token Affinity Access Token168 * @param {function} callback function(error, avatarUrl)169 * @return undefined170 */171wsod.getAffinityAvatarUrl = function ( token, callback ) {172 this.affinityAssertion( token, function ( error, response, body ) {173 if ( error || response.statusCode != 200 ) {174 logger.log( "error", "affinityAssertion: " + error );175 return callback( error || true );176 }177 var assertion = body.affinityAssertion.assertion;178 wsod.affinitySession( assertion, function ( error, response, body ) {179 if ( error || response.statusCode != 200 ) {180 logger.log( "error", "affinitySession: " + error );181 return callback( error || true );182 }183 var affinity_access_token = body.affinityToken;184 var avatarUrl = wsod.affinityAvatarUrl( affinity_access_token );185 callback( false, {186 avatarUrl: avatarUrl,187 access_token: affinity_access_token188 } );189 } );190 } );191};192/**193 * Request the affinity Url and if the response code is 200 then stream back the194 * contents of the image, otherwise call next which should invoke the next express route195 * available196 */197wsod.streamAffinityAvatar = function ( token, response, next ) {198 var avatarUrl = wsod.affinityAvatarUrl( token );199 var nextCalled = false;200 var callNext = function () {201 if ( nextCalled ) {202 return;203 }204 nextCalled = true;205 next();206 };207 var options = {208 uri: avatarUrl,209 timeout: this.TIMEOUT210 };211 logger.log( "debug2", 'WSOD streamAffinityAvatar request ', options );212 try {213 var req = request( options ).on( 'response',function ( res ) {214 if ( res.statusCode == 200 ) {215 logger.log( "debug2", 'WSOD streamAffinityAvatar streaming ', options );216 req.pipe( response );217 }218 else {219 callNext();220 }221 } ).on( 'error', function ( ex ) {222 logger.log( 'warning', 'streamAffinityAvatar exception: ' + ex );223 callNext();224 } );225 }226 catch ( ex ) {227 logger.log( 'warning', 'streamAffinityAvatar exception: ' + ex );228 callNext();229 }230};231wsod.affinityIdFromToken = function ( token ) {232 if ( token && token.indexOf( ":" ) ) {233 return token.split( ":" )[0];234 }235};236function parseJsonBody( error, response, body ) {237 if ( !error && response.headers["content-type"].indexOf( "application/json" ) === 0 ) {238 return JSON.parse( body );239 }240 else {241 return body;242 }...

Full Screen

Full Screen

handlers.js

Source:handlers.js Github

copy

Full Screen

...9 return token10}1112async function signUp(req, res) {13 const {nachname, vorname, user, email, pw} = await parseJsonBody(req)1415 if(!email) {16 return respondWithJson(res, {ok: false, info: "email must not be empty"})17 }18 if(doesItemExist(user)) {19 return respondWithJson(res, {ok: false, info: "user already exists"})20 }2122 const saltedpassword = pw + "jgf75rg67d54dh5zrfuztg6rdtw4sv4t5dhfntuzho9kkhunutfg65df6";23 24 const hash = await bcrypt.hash(saltedpassword, 10)25 26 await save(`${user}/userdata.json`, {user, hash, email, nachname, vorname})27 const token = await createToken(user)28 respondWithJson(res, {ok: true, data: {user, email, vorname, nachname, token}})29}3031async function signIn(req, res) {32 const {user, pw} = await parseJsonBody(req)33 const userdata = await load(`${user}/userdata.json`)34 const {email, vorname, nachname, hash} = userdata35 saltedpassword = pw + "jgf75rg67d54dh5zrfuztg6rdtw4sv4t5dhfntuzho9kkhunutfg65df6";36 const passwordsMatch = await bcrypt.compare(saltedpassword, hash)37 const token = await createToken(user)38 respondWithJson(res, {ok: passwordsMatch, data: {email, user, vorname, nachname, token}})39}4041async function verifyToken(user, token) {42 const saved = await load(`${user}/token.json`)43 return saved.token == token44}4546async function saveData(req, res) {47 const {path, data, user, token} = await parseJsonBody(req)48 if(!await verifyToken(user, token)) return respondWithJson(res, {ok: false, info: "TokenMismatch"})49 await save(path, data)50 respondWithJson(res, {ok: true})51}5253async function loadData(req, res) {54 const {path, user, token} = await parseJsonBody(req)55 if(!await verifyToken(user, token)) return respondWithJson(res, {ok: false, info: "TokenMismatch"})56 respondWithJson(res, await load(path))57}5859async function deleteItem(req, res) {60 const {path, user, token} = await parseJsonBody(req)61 if(!await verifyToken(user,token)) return respondWithJson(res, {ok: false, info: "TokenMismatch"})62 respondWithJson(res, await remove(path))63}6465async function loadAll(req, res) {66 const {path, user, token} = await parseJsonBody(req)67 if(!await verifyToken(user, token)) return respondWithJson(res, {ok: false, info: "TokenMismatch"})68 try {69 const files = await load(path)70 const items = []71 for(var f of files) {72 if(f.endsWith(".json")) {73 var item = await load(path + "/" + f)74 item.id = f75 items.push(item)76 }77 }78 respondWithJson(res, items)79 }80 catch(e) { ...

Full Screen

Full Screen

router.js

Source:router.js Github

copy

Full Screen

1const body_parser = require('body-parser')2const morgan_body = require('morgan-body');3const auth_anonymus = require('./auth/anonymus.js');4const auth_google = require('./auth/google.js');5const auth_fb = require('./auth/fb.js');6const method_account = require('./methods/account.js')7const method_stats = require('./methods/stats.js')8const method_track = require('./methods/track.js')9const method_check_token = require('./methods/check_token.js')10const update_gender = require('./update/gender.js')11const update_stats = require('./update/stats.js')12const update_date_birth = require('./update/date_birth.js')13const update_health_status = require('./update/health_status.js')14var parseJsonBody = function (req, res, next) {15 try {16 req.body = JSON.parse(req.body);17 next();18 } catch (err) {19 res.json({ 'error': "could not parse json" });20 }21};22module.exports.initialize = (app, db, geo) => {23 morgan_body(app);24 const provide_db = (req, res, next) => {25 req.db = db;26 req.geo = geo;27 next();28 };29 app.post('/auth/anonymus', provide_db, auth_anonymus);30 app.post('/auth/google', provide_db, body_parser.text(), parseJsonBody, auth_google);31 app.post('/auth/fb', provide_db, body_parser.text(), parseJsonBody, auth_fb);32 const provide_user = async function(req, res, next) {33 try {34 const token = req.body.token;35 if (!token)36 return res.json({ 'error': 'no access token' });37 req.user = await db.User.findOne({token: token});38 if (!req.user)39 return res.json({ 'error': 'invalid access token' });40 next();41 } catch (err) {42 console.error(err);43 res.status(500).json({44 'error': 'Internal server error'45 });46 }47 };48 app.post('/account', provide_db, body_parser.text(), parseJsonBody, provide_user, method_account);49 app.post('/stats', provide_db, body_parser.text(), parseJsonBody, provide_user, method_stats);50 app.post('/track', provide_db, body_parser.text(), parseJsonBody, provide_user, method_track);51 app.post('/check_token', provide_db, body_parser.text(), parseJsonBody, provide_user, method_check_token);52 app.post('/update/gender', provide_db, body_parser.text(), parseJsonBody, provide_user, update_gender);53 app.post('/update/stats', provide_db, body_parser.text(), parseJsonBody, provide_user, update_stats);54 app.post('/update/date_birth', provide_db, body_parser.text(), parseJsonBody, provide_user, update_date_birth);55 app.post('/update/health_status', provide_db, body_parser.text(), parseJsonBody, provide_user, update_health_status);56 console.log('Routes initialized!');...

Full Screen

Full Screen

consumer.server.utils.js

Source:consumer.server.utils.js Github

copy

Full Screen

1'use strict';2const logger = require('../../config/logger');3const emailsMapSingleton = require('../services/emailsMap.services.server');4exports.onMessage = (message) => {5 const payload = message.value;6 const headers = parseHeaders(payload);7 const messageType = headers['Message-Type'];8 const messageId = headers['Message-Id'];9 const messageTimestamp = headers['Message-Timestamp'];10 switch (messageType) {11 case 'UserUpdated':12 logger.debug('Message Accepted:', messageType, messageTimestamp, messageId);13 addToMap(payload);14 break;15 case 'UserCreated':16 logger.debug('Message Accepted:', messageType, messageTimestamp, messageId);17 addToMap(payload);18 break;19 case 'UserSynchronised': //This is temporary. Waiting to ERights to be deprecated20 logger.debug('Message Accepted:', messageType, messageTimestamp, messageId);21 addToMap(payload);22 break;23 case 'Ping':24 logger.silly('Message Rejected:', messageType, messageTimestamp, messageId);25 break;26 default:27 logger.silly('Message Rejected:', messageType, messageTimestamp, messageId);28 break;29 }30};31exports.onError = (err) => {32 logger.error(err);33 if (err.name === 'FailedToRebalanceConsumerError' || err.name === 'FailedToRegisterConsumerError' || err.name === 'BrokerNotAvailableError') {34 process.exit();35 }36};37exports.parseHeaders = parseHeaders;38exports.parseJSONBody = parseJSONBody;39exports.addToMap = exports;40function parseHeaders (payload) {41 const bits = payload.split('\r\n\r\n');42 const rawHeaders = bits[0].split('\r\n');43 let headers = {};44 for (let header of rawHeaders) {45 let headerBits = header.match(/^([^:]+): (.*)$/);46 if (headerBits && headerBits[1] && headerBits[2]) {47 headers[headerBits[1]] = headerBits[2];48 }49 }50 return headers;51}52function parseJSONBody (payload) {53 const bits = payload.split('\r\n\r\n');54 return JSON.parse(bits[1]);55}56function addToMap(payload) {57 let body = parseJSONBody(payload);58 emailsMapSingleton.set(body.user.id, {59 email: body.user.email,60 firstName: body.user.firstName,61 lastName: body.user.lastName62 });...

Full Screen

Full Screen

server.js

Source:server.js Github

copy

Full Screen

...10 db,11 pendingTimeout: opts.pendingTimeout12 })13 // post new message14 app.post('/message/new', parseJsonBody(), (req, res, next) => {15 const { payload } = req.body16 mq.addNewMessage(payload)17 .then(id => res.json({ id }))18 .catch(err => next(err))19 })20 // request the next available message21 app.get('/message/next', (req, res, next) => {22 mq.getNextMessage()23 .then(message => res.json(message))24 .catch(err => next(err))25 })26 // post that certain message has been processed27 app.post('/message/:id/status/done', (req, res, next) => {28 const { id: idFromUrl } = req.params...

Full Screen

Full Screen

user.js

Source:user.js Github

copy

Full Screen

...5exports.getAllUsers = async () => {6 return await modelUser.allUsersModel();7};8exports.addNewUser = async (req) => {9 const newUserBody = await parseJsonBody(req);10 const user = {11 id: createId(),12 ...newUserBody,13 };14 await modelUser.createNewUserModel(user);15 return user;16};17exports.getUserById = async (id, res) => {18 const getAllPets = await modelPets.getAllPetsModel();19 return await modelUser.getUserByIdModel(id, getAllPets);20};21exports.updateUser = async (req) => {22 const updateUserData = await parseJsonBody(req);23 await modelUser.updateUserModel(updateUserData);24 return updateUserData;25};26exports.deleteUser = async (req) => {27 const deleteUserData = await parseJsonBody(req);28 await modelPets.deleteOwnerPet(deleteUserData.id);29 await modelUser.deleteUserModel(deleteUserData);30 return deleteUserData;...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const router = require('express').Router();2const bodyParser = require('body-parser');3const { gateForAdmin } = require('../../utils/auth');4const numbers = require('./numbers');5const events = require('./events');6const metrics = require('./metrics');7const parseJsonBody = bodyParser.json();8router.get('/numbers', numbers.get);9router.get('/events', events.get);10router.get('/metrics/:eventId', metrics.get);11router.post(12 '/notification',13 gateForAdmin,14 parseJsonBody,15 require('./notification').handler16);17router.post('/numbers', gateForAdmin, parseJsonBody, numbers.post);18router.post('/events', gateForAdmin, parseJsonBody, events.create);19router.post('/reset', gateForAdmin, require('./reset').handler);20router.post('/setup', gateForAdmin, require('./setup').handler);21router.delete('/events/:eventId', gateForAdmin, events.delete);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2 it('test', () => {3 cy.request({4 body: {5 },6 }).then((response) => {7 expect(response.status).to.eq(201)8 expect(response.body).to.have.property('id')9 expect(response.body).to.have.property('title', 'foo')10 expect(response.body).to.have.property('body', 'bar')11 expect(response.body).to.have.property('userId', 1)12 })13 })14})15describe('Test', () => {16 it('test', () => {17 cy.request({18 body: {19 },20 }).then((response) => {21 expect(response.status).to.eq(201)22 expect(response.body).to.have.property('id')23 expect(response.body).to.have.property('title', 'foo')24 expect(response.body).to.have.property('body', 'bar')25 expect(response.body).to.have.property('userId', 1)26 })27 })28})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', () => {2 it('test', () => {3 cy.request({4 body: { title: 'foo', body: 'bar', userId: 1 },5 headers: { 'content-type': 'application/json' },6 }).then((response) => {7 expect(response.body).to.have.property('title', 'foo')8 expect(response.body).to.have.property('body', 'bar')9 expect(response.body).to.have.property('userId', 1)10 })11 })12})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('API Testing', () => {2 it('POST Request', () => {3 cy.request({4 body: {5 }6 }).then(response => {7 expect(response.status).to.eq(201)8 expect(response.body).to.have.property('name', 'morpheus')9 expect(response.body).to.have.property('job', 'leader')10 })11 })12})13describe('API Testing', () => {14 it('POST Request', () => {15 cy.request({16 body: {17 }18 }).then(response => {19 expect(response.status).to.eq(201)20 expect(response.body).to.have.property('name', 'morpheus')21 expect(response.body).to.have.property('job', 'leader')22 })23 })24})25describe('API Testing', () => {26 it('POST Request', () => {27 cy.request({28 body: {29 }30 }).then(response => {31 expect(response.status).to.eq(201)32 expect(response.body).to.have.property('name', 'morpheus')33 expect(response.body).to.have.property('job', 'leader')34 })35 })36})37describe('API Testing', () => {38 it('POST Request', () => {39 cy.request({40 body: {41 }42 }).then(response => {43 expect(response.status).to.eq(201)44 expect(response.body).to.have.property('name', 'morpheus')45 expect(response.body).to.have.property('job',

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2 it('test', () => {3 cy.server();4 cy.route('POST', '**/comments').as('postComment');5 cy.get('.network-post').click();6 cy.wait('@postComment').then((xhr) => {7 expect(xhr.requestBody).to.include('email');8 expect(xhr.requestHeaders).to.have.property('Content-Type');9 expect(xhr.responseBody).to.have.property('name', 'Using POST in cy.route()');10 });11 });12});

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.request({2 body: {3 },4}).then((response) => {5 expect(response.body).to.deep.equal({6 })7})8cy.request(url, body)9cy.parseJsonBody(response)10cy.parseXmlBody(response)11[MIT](

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("Test", () => {2 it("test", () => {3 cy.request({4 body: {5 },6 })7 .its("body")8 .then((res) => {9 cy.log(res);10 });11 });12});

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('parseJsonBody', (response) => {2 return cy.task('parseJsonBody', response);3});4Cypress.Commands.add('parseJsonBody', (response) => {5 return cy.task('parseJsonBody', response);6});7module.exports = (on, config) => {8 on('task', {9 parseJsonBody(response) {10 return JSON.parse(response.body);11 }12 });13};14require('cypress-xpath');15require('cypress-plugin-tab');16require('@4tw/cypress-drag-drop');17require('cypress-file-upload');18require('cypress-iframe');19require('cypress-plugin-snapshots/commands');20require('cypress-xpath');21require('cypress-plugin-tab');22require('@4tw/cypress-drag-drop');23require('cypress-file-upload');24require('cypress-iframe');25require('cypress-plugin-snap

Full Screen

Using AI Code Generation

copy

Full Screen

1import * as cypressType from 'cypress/types/index';2import * as cypress from 'cypress';3import { readFileSync } from 'fs';4import { join } from 'path';5declare global {6 namespace Cypress {7 interface Chainable<Subject> {8 parseJsonBody(): Chainable<any>;9 }10 }11}12namespace Cypress {13 interface Chainable<Subject> {14 parseJsonBody(): Chainable<any>;15 }16}17const getBody = (response: cypressType.Response) => {18 const body = response.body;19 if (body === undefined) {20 throw new Error('Response body is undefined');21 }22 return body;23};24const parseJsonBody = (response: cypressType.Response) => {25 const body = getBody(response);26 if (typeof body === 'string') {27 return JSON.parse(body);28 }29 return body;30};31const parseXmlBody = (response: cypressType.Response) => {32 const body = getBody(response);33 if (typeof body === 'string') {34 return Cypress.$.parseXML(body);35 }36 return body;37};38const parseYamlBody = (response: cypressType.Response) => {39 const body = getBody(response);40 if (typeof body === 'string') {41 return Cypress.yaml.parse(body);42 }43 return body;44};45const parseBody = (response: cypressType.Response) => {46 const body = getBody(response);47 if (typeof body === 'string') {48 return body;49 }50 return body;51};52Cypress.Commands.add('parseJsonBody', { prevSubject: 'response' }, parseJsonBody);53Cypress.Commands.add('parseXmlBody', { prevSubject: 'response' }, parseXmlBody);54Cypress.Commands.add('parseYamlBody', { prevSubject: 'response' }, parseYamlBody);55Cypress.Commands.add('parseBody', { prevSubject: 'response' }, parseBody);56declare global {57 namespace Cypress {58 interface Chainable<Subject> {59 getTestFile(fileName: string): Chainable<any>;60 }61 }

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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